是否可以从支持配置文件(HDD、Spp 和音频)中获取连接的设备列表。要求就像我的设备将支持 HDD、SPP 和音频,所以我必须过滤支持所有这些配置文件的设备。无论如何过滤设备?
最佳答案
是的,这是可能的,但您的 Android 应用程序必须以 SDK 11 或更高版本为目标 (Android 3.0.X)。
您的问题的解决方案是您必须查询您的 Android 设备已知的所有 BluetoothDevices。 已知是指所有配对的已连接或未连接的设备以及未配对的已连接设备。
我们稍后会过滤掉未连接的设备,因为您只需要当前连接的设备。
- 首先您需要获取
BluetoothAdapter
:
final BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
- 其次,您需要确保蓝牙可用并已打开:
if (btAdapter != null && btAdapter.isEnabled()) // null means no Bluetooth!
如果未打开蓝牙,您可以使用文档中不推荐的 btAdapter.enable()
或要求用户这样做:Programmatically enabling bluetooth on Android
- 第三,你需要定义一个状态数组(过滤掉 未连接的设备):
final int[] states = new int[] {BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_CONNECTING};
第四,您创建一个
BluetoothProfile.ServiceListener
,它 包含连接服务时触发的两个回调和 断开连接:final BluetoothProfile.ServiceListener listener = new BluetoothProfile.ServiceListener() { @Override public void onServiceConnected(int profile, BluetoothProfile proxy) { } @Override public void onServiceDisconnected(int profile) { } };
现在,由于您必须对 Android SDK (A2Dp, GATT, GATT_SERVER, Handset, Health, SAP) 中所有可用的蓝牙配置文件重复查询过程,因此您应该按以下步骤进行:
在 onServiceConnected
中,放置一个检查当前配置文件的条件,以便我们将找到的设备添加到正确的集合中,我们使用:proxy.getDevicesMatchingConnectionStates(states)
过滤掉未连接的设备:
switch (profile) {
case BluetoothProfile.A2DP:
ad2dpDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
break;
case BluetoothProfile.GATT: // NOTE ! Requires SDK 18 !
gattDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
break;
case BluetoothProfile.GATT_SERVER: // NOTE ! Requires SDK 18 !
gattServerDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
break;
case BluetoothProfile.HEADSET:
headsetDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
break;
case BluetoothProfile.HEALTH: // NOTE ! Requires SDK 14 !
healthDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
break;
case BluetoothProfile.SAP: // NOTE ! Requires SDK 23 !
sapDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
break;
}
最后,要做的最后一件事是开始查询过程:
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.A2DP);
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.GATT); // NOTE ! Requires SDK 18 !
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.GATT_SERVER); // NOTE ! Requires SDK 18 !
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.HEADSET);
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.HEALTH); // NOTE ! Requires SDK 14 !
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.SAP); // NOTE ! Requires SDK 23 !
关于android - 如何从特定的蓝牙配置文件中获取连接的设备列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34766638/