如何以编程方式检查Android中蓝牙设备的连接状态?

Ray*_*Xie 10 android bluetooth

我可以枚举配对Bluetooth设备,我需要在应用启动时检查它们当前的连接状态.

但是,我发现无法获得连接状态?!

以下是我尝试但失败的一些努力:

  1. android.bluetooth.BluetoothDevice

它有获得远程设备的键状态的方法,和用于键状态可能值如下:BOND_NONE,BOND_BONDING,BOND_BONDED.但这不是连接状态.

  1. android.bluetooth.BluetoothProfile

该方法可用于获取连接状态,但BluetoothProfile必须首先获取对象.

public abstract int getConnectionState (BluetoothDevice device); 
Run Code Online (Sandbox Code Playgroud)

正如在doc中描述的那样:" 客户端应调用getProfileProxy(Context,BluetoothProfile.ServiceListener,int),以获取配置文件代理. ",它只能ServiceListener在状态发生变化时在被调用时进行检索.

如果我在启动时查询状态而没有发生任何状态更改,该怎么办?

  1. android.bluetooth.BluetoothManager

它提供了一种方法:

public int getConnectionState (BluetoothDevice device, int profile);
Run Code Online (Sandbox Code Playgroud)

但是它不能被用于检测连接状态的的Bluetooth扬声器,作为配置文件参数只接受GATT或GATT_SERVER(用于低能量设备),其他轮廓(HEADSET,HEALTH,A2DP)不被支持.

  1. android.bluetooth.BluetoothAdapter

它提供了一种方法:

public int getProfileConnectionState (int profile);
Run Code Online (Sandbox Code Playgroud)

此功能可用于检查本地Bluetooth适配器是否连接到特定配置文件的任何远程设备.它可用于检查指定的配置文件.但它不能用于检查给定的设备.

有谁知道如何获得给定Bluetooth设备的连接状态?

提前致谢.

Ale*_*Ale 1

请参阅类似问题的答案中的注释如何以编程方式判断蓝牙设备是否已连接?(安卓2.2):

  • 无法在应用程序启动时检索已连接设备的列表。蓝牙 API 不允许您查询,而是允许您监听更改。
  • 解决上述问题的一种方法是检索所有已知/配对设备的列表...然后尝试连接到每个设备(以确定您是否已连接)。或者,您可以让后台服务监视蓝牙 API 并将设备状态写入磁盘以供您的应用程序稍后使用。