我是低功耗蓝牙 (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/