【问题标题】:Get list of connected Bluetooth LE devices获取已连接的蓝牙 LE 设备列表
【发布时间】:2014-12-17 03:31:53
【问题描述】:

我是蓝牙低功耗 (LE) API 的新手。有没有办法检查 Android 设备当前是否连接到任何蓝牙 LE 设备并可能获取这些设备的列表?

BT-LE 设备是否真的“连接”了?我注意到当我的智能手表与我的 Nexus 5 配对/连接时,蓝牙图标在状态栏中(在 KitKat 上)没有变成白色/粗体,就像连接到经典蓝牙设备时一样。

我将以下代码用于经典设备。看起来我可以以相同的方式检查 GATT 和 GATT_SERVER,但它们总是返回断开连接。

更新:既然我已经将 Android Lollipop 刷到了我的 Nexus 5,我认为它一定是可能的,因为它用于 SmartLock,并且它以某种方式检测到我的 BT-LE Android 手表已连接。

private BluetoothAdapter getBTAdapter() {       
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2)
        return BluetoothAdapter.getDefaultAdapter();
    else {
        BluetoothManager bm = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
        return bm.getAdapter();
    }
}

public boolean isBluetoothConnected() {
    if(mBluetoothAdapter == null || 
            (mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET) == BluetoothProfile.STATE_DISCONNECTED 
                && mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.A2DP) == BluetoothProfile.STATE_DISCONNECTED
                && mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEALTH) == BluetoothProfile.STATE_DISCONNECTED)

            ) {

        Utils.logDebug(TAG, "GATT_SERVER " + mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.GATT_SERVER));
        Utils.logDebug(TAG, "GATT " + mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.GATT));
        return false;
    }
    return true;
}

【问题讨论】:

    标签: android bluetooth bluetooth-lowenergy android-5.0-lollipop


    【解决方案1】:

    你可以用这个:

    BluetoothManager bluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
    List<BluetoothDevice> devices = bluetoothManager.getConnectedDevices(BluetoothProfile.GATT);
    for(BluetoothDevice device : devices) {
      if(device.getType() == BluetoothDevice.DEVICE_TYPE_LE) {
         ...
      }
    }
    

    如果您的手表确实已连接,我无法回答。可能是您的手表只宣传其状态,而手机正在收听此广告。这取决于它是如何实现的。

    【讨论】:

    • 感谢您的建议。我试过了,但不幸的是它没有返回任何设备,即使智能手表已“连接”。我认为 BT-LE 设备不会一直“连接”,而是来回通知设备......
    • 是的。那是可能的。永久保持连接会增加电池消耗,因此最好设计为定期进行...
    • 现在我已经将 Android Lollipop 刷到了我的 Nexus 5,我认为它一定是可能的,因为它用于 SmartLock,并且它以某种方式检测到我的 BT-LE Android Watch 已连接。
    • 别忘了检查 BluetoothDevice.DEVICE_TYPE_DUAL
    • 我有一个类似的问题 - 上面的代码没有返回任何东西,无论是 LE 还是普通设备,即使状态栏中的蓝牙图标显示设备已连接。可能是耳机配置文件(扬声器)? Fitbit 也不显示。
    【解决方案2】:

    您的 BTLE 设备可以在系统中使用不同的配置文件进行注册。 Android 的 API 只公开了一些配置文件(GATT、GATT_SERVER、Headset 等)。但是,还有其他配置文件可以注册为系统,例如 INPUT_DECVICE。调用 getConnectedDevices() 仅适用于 GATT 和 GATT_SERVER 配置文件,但如果您的设备注册为任何其他配置文件,则该方法将不起作用。

    【讨论】:

      猜你喜欢
      • 2019-01-02
      • 2014-10-04
      • 2018-11-16
      • 1970-01-01
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-31
      相关资源
      最近更新 更多