android – 如何以编程方式判断蓝牙设备是否已连接?
作者:互联网
我知道如何获得配对设备列表,但我怎么知道它们是否已连接?
它必须是可能的,因为我看到它们列在我手机的蓝牙设备列表中,并说明了它们的连接状态.
解决方法:
为您的AndroidManifest添加蓝牙权限,
<uses-permission android:name="android.permission.BLUETOOTH" />
然后使用intent过滤器来监听ACTION_ACL_CONNECTED,ACTION_ACL_DISCONNECT_REQUESTED和ACTION_ACL_DISCONNECTED广播:
public void onCreate() {
...
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver, filter);
}
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
... //Device found
}
else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
... //Device is now connected
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
... //Done searching
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
... //Device is about to disconnect
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
... //Device has disconnected
}
}
};
几点说明:
>在应用程序启动时无法检索已连接设备的列表.蓝牙API不允许您进行查询,而是允许您收听更改.
>对上述问题的一个不好的工作是检索所有已知/配对设备的列表…然后尝试连接到每个设备(以确定您是否已连接).
>或者,您可以让后台服务观看蓝牙API并将设备状态写入磁盘,以便您的应用程序在以后使用.
标签:android-bluetooth,android 来源: https://codeday.me/bug/20190911/1804306.html