Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically check connection state of a Bluetooth device in Android?

I can enumerate the paired Bluetooth devices, and I need to check their current connection state on app startup.

But, I found no way of getting the connection state ?!

Here are some efforts I've tried but failed:

  1. android.bluetooth.BluetoothDevice

It has the method to get the bond state of the remote device, and possible values for the bond state are: BOND_NONE, BOND_BONDING, BOND_BONDED. But it's not the connection state.

  1. android.bluetooth.BluetoothProfile

The method can be used to get the connection state, but the BluetoothProfile object must be obtained first.

public abstract int getConnectionState (BluetoothDevice device); 

As describe in doc: "Clients should call getProfileProxy(Context, BluetoothProfile.ServiceListener, int), to get the Profile Proxy.", it can ONLY be retrieve in a ServiceListener called when state changes.

What if I query the state on startup without any state changes happen yet?

  1. android.bluetooth.BluetoothManager

It provides a method:

public int getConnectionState (BluetoothDevice device, int profile);

But it cannot be used to detect connection state of a Bluetooth speaker, as the profile argument only accepts GATT or GATT_SERVER (for low energy device), other profiles (HEADSET, HEALTH, A2DP) are not supported.

  1. android.bluetooth.BluetoothAdapter

It provides a method:

public int getProfileConnectionState (int profile);

This function can be used to check whether the local Bluetooth adapter is connected to any remote device for a specific profile. It can be used to check a specified profile. But it cannot be used to check a given device.

Does anyone know how to get the connection state of a given Bluetooth device?

Thanks in advance.

like image 471
Raymond Xie Avatar asked Sep 11 '14 02:09

Raymond Xie


1 Answers

See the notes in the answer from similar question How to programmatically tell if a Bluetooth device is connected? (Android 2.2):

  • There is no way to retrieve a list of connected devices at application startup. The Bluetooth API does not allow you to QUERY, instead it allows you to listen to CHANGES.
  • A hoaky work around to the above problem would be to retrieve the list of all known/paired devices... then trying to connect to each one (to determine if you're connected). Alternatively, you could have a background service watch the Bluetooth API and write the device states to disk for your application to use at a later date.
like image 171
Ale Avatar answered Oct 21 '22 12:10

Ale