Sai*_*ath 1 android android-bluetooth bluetooth-profile
无论如何可以从支持配置文件(HDD、Spp 和音频)中获取连接的设备列表。要求就像我的设备将支持 HDD、SPP 和音频,所以我必须过滤支持所有这些配置文件的设备。反正有过滤设备吗?
是的,这是可能的,但您的 Android 应用程序必须面向SDK 11 或更高版本 ( Android 3.0.X )。
您的问题的解决方案是您必须查询您的 Android 设备已知的所有蓝牙设备。由知名我的意思是所有配对连接,或者未连接设备和不成连接的设备。
我们稍后会过滤掉未连接的设备,因为您只需要当前连接的设备。
BluetoothAdapter:final BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter != null && btAdapter.isEnabled()) // null 表示没有蓝牙!
如果蓝牙没有出现,您可以使用btAdapter.enable()文档中不推荐的方法或要求用户这样做:以编程方式在 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) {
}
};
Run Code Online (Sandbox Code Playgroud)现在,由于您必须对 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;
}
Run Code Online (Sandbox Code Playgroud)
最后,最后要做的是开始查询过程:
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 !
Run Code Online (Sandbox Code Playgroud)