【问题标题】:How to programmatically check connection state of a Bluetooth device in Android?如何以编程方式检查 Android 中蓝牙设备的连接状态?
【发布时间】:2014-09-11 02:36:22
【问题描述】:

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

但是,我找不到获取连接状态的方法?!

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

  1. android.bluetooth.BluetoothDevice

它具有获取远程设备绑定状态的方法,绑定状态的可能值为:BOND_NONEBOND_BONDINGBOND_BONDED。但这不是连接状态。

  1. android.bluetooth.BluetoothProfile

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

public abstract int getConnectionState (BluetoothDevice device); 

如文档中所述:“客户端应调用 getProfileProxy(Context, BluetoothProfile.ServiceListener, int),以获取配置文件代理。”,它只能在 ServiceListener 调用时检索状态变化。

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

  1. android.bluetooth.BluetoothManager

它提供了一个方法:

public int getConnectionState (BluetoothDevice device, int profile);

但它不能用于检测Bluetooth 扬声器的连接状态,因为配置文件参数只接受GATTGATT_SERVER(用于低能耗设备),其他配置文件(HEADSETHEALTHA2DP) 不受支持。

  1. android.bluetooth.BluetoothAdapter

它提供了一个方法:

public int getProfileConnectionState (int profile);

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

有人知道如何获取给定Bluetooth 设备的连接状态吗?

提前致谢。

【问题讨论】:

  • 你找到答案了吗?
  • 对这两天的帮助感到非常感激。您是否找到任何解决方案。我想检查蓝牙 gatt 连接状态是否已连接,然后需要等到它进入断开状态,但我使用了 getConnectionState() 它会引发异常。

标签: android bluetooth


【解决方案1】:

查看类似问题How to programmatically tell if a Bluetooth device is connected? (Android 2.2)的答案中的注释:

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

【讨论】:

    猜你喜欢
    • 2016-07-19
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-13
    • 2011-07-07
    相关资源
    最近更新 更多