Search code examples
androidbluetooth

How to find out if bluetooth is connected?


Can someone teach me how can I find out if bluetooth is connected to other device (mobile, headset, etc.)


Solution

  • I don't know of any way to get a list of currently connected devices, but you can listen for new connections using the ACL_CONNECTED intent: http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#ACTION_ACL_CONNECTED

    This intent includes an extra field with the remote device that the connection is with.

    On Android, all Bluetooth connections are ACL connections, so registering for this intent will get you all new connections.

    So, your receiver would look something like this:

    public class ReceiverBlue extends BroadcastReceiver {
      public final static String CTAG = "ReceiverBlue";
      public Set<BluetoothDevice> connectedDevices = new HashSet<BluetoothDevice>();
    
      public void onReceive(Context ctx, Intent intent) {
    
        final BluetoothDevice device = intent.getParcelableExtra( BluetoothDevice.EXTRA_DEVICE );
    
        if (BluetoothDevice.ACTION_ACL_CONNECTED.equalsIgnoreCase( action ) )   {
          Log.v(CTAG, "We are now connected to " + device.getName() );
          if (!connectedDevices.contains(device))
            connectedDevices.add(device);
        }
    
        if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equalsIgnoreCase( action ) )    {
          Log.v(CTAG, "We have just disconnected from " + device.getName() );
          connectedDevices.remove(device);
        }
      }
    }