android - 获取已连接的蓝牙 LE 设备列表

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

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

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

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

更新:现在我已经将 Android Lollipop 闪存到我的 Nexus 5,我认为这一定是可行的,因为它用于 SmartLock,并且它以某种方式检测到我的 BT-LE Android watch 已连接。

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;
}

最佳答案

你可以使用这个:

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) {
     ...
  }
}

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

关于android - 获取已连接的蓝牙 LE 设备列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26494648/

相关文章:

android - 如何使用 WorkManager 定期更换墙纸?

android - 如何以编程方式在蓝牙和听筒之间选择媒体音频

android - 使用低功耗蓝牙解锁 Linux

iOS蓝牙双模;同时将 BLE (GATT) 连接到已连接的 BR/EDR (A2DP/HFP) 立体声耳机

ios - 如何以 iOS 端为中心控制扫描请求?

java - 在设备中安装 Android 应用程序

android - 在编辑文本框中验证日期

android - Dagger-android 共享 Activity 之间的依赖关系

ios - iBeacon 应用程序 - 从 Iphone/Ipad 接收数据

c - 将 HCI 命令写入 USB BT Dongle