Search code examples
javaandroidandroid-studiobluetoothbroadcastreceiver

Programmatically connect Bluetooth Device in Android from Broadcast Receiver


In my Broadcast Receiver, I've retrieved a list of bonded bluetooth devices.

BluetoothStateChangedReceiver extends BroadcastReceiver

This is how I get the paired devices:

private void getPairedDevices(){
    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    if (pairedDevices == null || pairedDevices.size() == 0) {
        showToast("No Paired Devices Found");
    } else {
        ArrayList<BluetoothDevice> list = new ArrayList<BluetoothDevice>();
        list.addAll(pairedDevices);
        mPairedDeviceList = list;
    }
}

I call this code:

BluetoothDevice device = mPairedDeviceList.get(0);
            deviceName = device.getName();

            if(device.getBondState()==device.BOND_BONDED){
                Log.d(TAG,"Device Name"+device.getName());
                BluetoothSocket mSocket= null;
                try {
                    mSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
                } catch (IOException e1) {
                    Log.d(TAG,"socket not created");
                    e1.printStackTrace();
                }
                try{
                    mSocket.connect();
                }
                catch(IOException e) {
                    try {
                        mSocket.close();
                        Log.d(TAG, "Cannot connect");
                    } catch (IOException e1) {
                        Log.d(TAG, "Socket not closed");
                        e1.printStackTrace();
                    }

                }

            }

My UUID is

private static final UUID MY_UUID = UUID.fromString("DEADBEEF-0000-0000-0000-000000000000");

However, I came never able to get a connection to the devices?

I'm simply trying to connect to a bluetooth speaker programmatically once I turn on Bluetooth. What am I missing?


Solution

  • The method createInsecureRfcommSocketToServiceRecord has some issues on Android 2.1 and 2.2. The following code address these devices in the catch part:

    try {
            mBtSocket = btDevice
                    .createRfcommSocketToServiceRecord(BT_SRVC_UUID);
            mBtSocket.connect(); 
        } catch (Exception e) {
            Log.e(TAG, "createInsecureRfcommSocket", e);
            Log.d(TAG, "trying with reflection");
    
            BluetoothDevice hxm = BluetoothAdapter.getDefaultAdapter()
                    .getRemoteDevice(btDevice.getAddress());
            Method m;
            m = hxm.getClass().getMethod("createRfcommSocket",
                    new Class[] { int.class });
            mBtSocket = (BluetoothSocket) m.invoke(hxm, Integer.valueOf(1));
            mBtSocket.connect();
        }
    

    To get the btDevice and the BT_SRVC_UUID I use the following code:

    BluetoothDevice btDevice = BluetoothAdapter.getDefaultAdapter()
                .getRemoteDevice(macBtAddress);
    

    Finallly You should always ensure that the device is not performing device discovery when you call connect().

    mBluetoothAdapter.cancelDiscovery();
    

    To get the macBTAddress of a device you can use the bluetoothAdapter to search devices and get the mac addresses of previously paired devices. In the future the mac address will not change so you can save it.

    The BT_SRV_UUID is the id of your service. You can choose the UUID that you prefer just be sure that has a valid syntax (you can use the one suggested in my code).