Reputation: 1382
I'm just so confused... I mean let's say that after the user chooses the device he wants to be paired then how does my app finds the same app and send String data??? Then what's the API for receiving the event once data are sent???
A simple sample code would totally help me! (Please don't reference Google's Bluetooth Chat Example, they used design patterns which I'm not comfortable with yet).
Upvotes: 1
Views: 209
Reputation: 3593
Alright I will try to explain things as simple as possible.
Let's assume you are using an RFCOMM channel for communication between your two Android devices.
One device will act as a server, the other as a client.
public BluetoothServerSocket listenUsingRfcommWithServiceRecord (String name, UUID uuid)
where the name
is your app service name (choose any) and the uuid
is a java.util.UUID
that you choose too (here you have an online generator). Do not forget that UUID.
public BluetoothSocket accept (); //possibility to add a timeout parameter
Note: this is a blocking call meaning the thread that is running this code will block and wait until the method accept()
returns. It will only return when your client application connects to your server application. Use the timeout parameter if you do want to block forever (or for as long as your app is running). Since it's a blocking call, do not call it on your UI Thread it will cause an ANR (Application Not Responding). Instead use a Thread.
There is a two-case scenario : either your Android devices are paired, either they are not. The simplest way would be to manually pair your two devices via the Settings but unless you want perfect user experience for your app, use the discovery & binding operation.
Now onto the connexion to the server :
public BluetoothSocket createRfcommSocketToServiceRecord (UUID uuid);
public void connect (); //from the returned BluetoothSocket
Where the UUID is the one you use in your server application.
Note: again, connect()
is a blocking call, though it will not block forever because there is an internal timeout parameter. Call it from another Thread.
BluetoothSocket
(both server and client gets a socket).A guide to understand Stream and Bytes: http://fr.slideshare.net/shahjahan786/understanding-java-streams.
That's it. You have all the basic elements to work on your app and establish a Bluetooth connexion between two devices, wih your app, so that you can exchange data.
Upvotes: 1