Home > Blockchain >  BluetoothDevice how to know if a device is connected or disconnected
BluetoothDevice how to know if a device is connected or disconnected

Time:08-05

I have a list of bluetooth devices that I get from the bluetoothAdapter :

val bluetoothManager = ContextCompat.getSystemService(
        appContext,
        BluetoothManager::class.java
    ) as BluetoothManager
val bondedDevices = bluetoothManager.adapter.bondedDevices

After retrieving my list of bondedDevices, I tried to know the state of connection for all of them :

bondedDevices.forEach {
      when (val status = bluetoothManager.getConnectionState(it, BluetoothGatt.GATT)) {
                    BluetoothGatt.STATE_CONNECTED -> Log.d("DEBUG", "STATE_CONNECTED: $status")
                    BluetoothGatt.STATE_CONNECTING -> Log.d("DEBUG", "STATE_CONNECTING: $status")
                    BluetoothGatt.STATE_DISCONNECTED -> Log.d(
                        "DEBUG",
                        "STATE_DISCONNECTED: $status"
                    )
                    BluetoothGatt.STATE_DISCONNECTING -> Log.d(
                        "DEBUG",
                        "STATE_DISCONNECTING: $status"
                    )
                }
}

However, even if my device is connected to my phone, the status on the app will always be

BluetoothGatt.STATE_DISCONNECTED

Questions

  • Why the status is always BluetoothGatt.STATE_DISCONNECTED even if my device is connected to my phone?
  • I saw some topics about retrieving bluetooth connection at startup but it seems to be possible only with a listener, is that the only way ?

CodePudding user response:

You cannot query whether there is a Bluetooth connection in general. You need to know for which profile/service you want to know the connection status. Your code queries for a GATT connection which obviously does not exist. There are other profiles/services that your device could be connected to. See for example BluetoothAdapter.getProfileConnectionState()

The second approach is to wait for events when lower layer Bluetooth connections are established or disconnected. As you mention, this is only possible with a listener and only for the time your application is running.

CodePudding user response:

fun isBluetoothHeadsetConnected(): Boolean {
    val mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
    return (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled
        && mBluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothHeadset.STATE_CONNECTED)
}

Bluetooth connection is mandatory for this you'll need Bluetooth permission:

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