Connecting to a already paired Bluetooth device

Mazze picture Mazze · Jul 20, 2011 · Viewed 11.4k times · Source

Recently I tried to get a pairing process to work programatically and I succeded. But I recently found out that the users of my application can be connected to several of "interesting" devices. So I have to prompt the user to choose a device to connect to

So I have to connect the user to a already paired bluetooth device. But none of my efforts work. I tried running the pairing process again using the:

tmp = device.createRfcommSocketToServiceRecord(MY_UUID);

and also the following:

Method m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
mmSocket = (BluetoothSocket) m.invoke(mmDevice, 1);

which is the one I've implemented and the only working way to pair my phone with my embedded bluetooth device

So my question is:

  • Is it possible for me to disconnect a paired device and then connect to another embedded device? I tried.. to simply connect to the new device but I can't get that to work

Answer

stephendnicholas picture stephendnicholas · Jul 20, 2011

I'm afraid I'm not entirely sure what your problem is. Is it that you are unable to create a socket to an already paired bluetooth device?

First of all, if the device is already paired, you don't need to run the pairing process again. You just need to create the socket for communication, which will fail if the device is not available to communicate with. I've been doing some stuff around this lately and I've used the following code, which has worked fine for me:

    try {
        Method m = device.getClass().getMethod("createRfcommSocket",
                new Class[] { int.class });
        BluetoothSocket mySocket = (BluetoothSocket) m.invoke(device, Integer.valueOf(1));

    } catch (<VARIOUS EXCEPTIONS>) {
        //Do stuff
    }

For prompting the user to select which device, you can query the BluetoothAdapter for all the currently paired devices as follows:

Set<BluetoothDevice> bondedDevices = BluetoothAdapter
            .getDefaultAdapter().getBondedDevices();

Finally, it is possible to create connections to multiple devices at the same time - have a look here: Android Bluetooth API connect to multiple devices