First off, this approach will only handle incoming files. Not outgoing.
It would probably be better to add some checks in here, but to keep the code simple and easy to understand to the average Joe, I have left them out.
The first thing you want to do is create your class variables that will be used to create a server socket.
For this, you will need one class variable and two class constants, a name for your connection, the UUID, and a BluetoothAdapter object. The name can be whatever you want. It doesn't matter. The UUID has to follow a specific protocol. There are various UUID generators out there, or you could just use the one I supplied below.
- Code: Select all
private final String NAME = "MyName";
private final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66")
private BluetoothAdapter blueoothAdapter = null;
The next thing to do is to get the default bluetooth adapter. To do this, in your overrided onCreate() method, put the following:
- Code: Select all
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Next, we create a new thread that will establish a server socket.
This thread should look something like this:
- Code: Select all
private class AcceptThread implements Runnable
{
private BluetoothServerSocket serverSocket;
public AcceptThread()
{
//Temporary swap server socket for conditional
BluetoothServerSocket tmp = null;
try
{
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("MYNAME", MY_UUID);
}
catch(IOException e)
{
//handle exceptions here
}
//Swap server sockets
serverSocket = tmp;
}
public void run()
{
//Handle any non UI thread taks here and send a message back to the UI thread to handle UI activities
mHandler.sendEmptyMessage(0);
}
}
Next we need to start this thread as soon as the activity is created. To do this, add the following line at the end of the onCreate() method.
- Code: Select all
Thread acceptThread = new Thread(new AcceptThread());
acceptThread.start();
Also, we have the handler that is referenced in this thread.
- Code: Select all
private final Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
//Handle any UI changes here.
}
};
That's really it!
making a bluetooth connection and receiving files isn't as intimidating as it first may seem!

