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

4

我对蓝牙低功耗(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;
}
2个回答

7
您可以使用以下内容:
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) {
     ...
  }
}

我无法回答你的手表是否真正连接了。也许你的手表只是广告它的状态,而手机正在监听这些广告。这取决于它的实现方式。


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

1

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接