Android BluetoothHeadset getConnectedDevices() list is empty

951 Views Asked by At

In my app, I want to get certain details about the connected bluetooth headset. First, I thought of getting the connected devices whose profile is headset.

 val result =  BluetoothAdapter.getDefaultAdapter()
        .getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET)

The listener snippet is as follows :

private var mBluetoothHeadset: BluetoothHeadset? = null
private val mProfileListener = object : BluetoothProfile.ServiceListener {
    override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = proxy as BluetoothHeadset
            val devices = mBluetoothHeadset?.connectedDevices
            devices?.forEach {
                println(it.name)
            }
        }
    }

    override fun onServiceDisconnected(profile: Int) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = null
        }
    }
}

I have declared the necessary permissions in the manifest

 <uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

But mBluetoothHeadset?.connectedDevices is always returning an empty list. But in my tablet, the device is already connected to a bluetooth headset. Am I missing anything here?

1

There are 1 best solutions below

0
On

It looks like we can get the list of connected devices by filtering it based on the various connection states. The following snippet worked for me

 private val states = intArrayOf(
    BluetoothProfile.STATE_DISCONNECTING,
    BluetoothProfile.STATE_DISCONNECTED,
    BluetoothProfile.STATE_CONNECTED,
    BluetoothProfile.STATE_CONNECTING
)
private val mProfileListener = object : BluetoothProfile.ServiceListener {
    override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = proxy as BluetoothHeadset
            val devices = mBluetoothHeadset?.getDevicesMatchingConnectionStates(states)
            devices?.forEach {
                println("${it.name} ${it.bondState}")
            }
        }
    }