0

I am starting a service that registers broadcast receiver for BT device connect/disconnect. It seem to work just fine. Although, I ran into a problem. I need to detect if BT headset is already connected, so that I know a current state. I use code below, but it looks like it doesn't do its job:

// ...
// get BluetoothAdapter 
BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
// to tell if BT headset is connected
boolean isBtHeadsetOn = false;

// if device supports BT
if (ba != null) {
    // get list of paired devices
    Set<BluetoothDevice> devices = ba.getBondedDevices();

    if (devices != null) {
        // loop through devices
        for (BluetoothDevice device : devices) {
            // get device class
            BluetoothClass bc = device.getBluetoothClass();
            if (bc == null) continue;
            int devClass = bc.getDeviceClass();

            // check if device is handsfree, headphones or headset
            if (devClass == BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE || devClass == BluetoothClass.Device.AUDIO_VIDEO_HEADPHONES || devClass == BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET) {
                // yes, it is
                isBtHeadsetOn = true;
                break;
            }
        }
    }
}

// now I got my result in variable isBtHeadsetOn
// ...

I am developing for android 2.1 and code above is placed in Service#onCreate(). Thanks for your help.

overbet13
  • 1,654
  • 1
  • 20
  • 36
Perry_ml
  • 495
  • 5
  • 16

1 Answers1

0

This code only gives you the bonded devices but not the connection status. This means, the bluetooth devices that your mobile remember... but they could be connected or not.

In general to know the status you should capture the change on the device state:

<receiver android:name=".receiver.BTReceiver">
        <intent-filter>
            <action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
            <action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
            <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
            <action android:name="android.bluetooth.device.action.BOND_STATE_CHANGED" />
        </intent-filter>

If you know that is a handsfree you could get a BluetoothHeadset object which actually has some methods to know connection status: http://developer.android.com/reference/android/bluetooth/BluetoothHeadset.html

Carlos Verdes
  • 3,037
  • 22
  • 20