如何以编程方式判断是否已连接蓝牙设备? [英] How to programmatically tell if a Bluetooth device is connected?
本文介绍了如何以编程方式判断是否已连接蓝牙设备?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我了解如何获取已配对设备的列表,但是如何知道它们是否已连接?
I understand how to get a list of paired devices but how can I tell if they are connected?
因为我在手机的蓝牙设备列表中看到了它们,并指出了它们的连接状态,所以这一定是可能的.
It must be possible since I see them listed in my phone's Bluetooth device list and it states their connection status.
推荐答案
向您的AndroidManifest添加蓝牙权限,
Add bluetooth permission to your AndroidManifest,
<uses-permission android:name="android.permission.BLUETOOTH" />
然后使用意图过滤器收听ACTION_ACL_CONNECTED
,ACTION_ACL_DISCONNECT_REQUESTED
和ACTION_ACL_DISCONNECTED
广播:
Then use intent filters to listen to the ACTION_ACL_CONNECTED
, ACTION_ACL_DISCONNECT_REQUESTED
, and ACTION_ACL_DISCONNECTED
broadcasts:
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
}
}
};
一些注意事项:
A few notes:
- 在应用程序启动时无法检索已连接设备的列表.蓝牙API不允许您查询,而是允许您收听更改.
- 解决上述问题的麻烦方法是检索所有已知/已配对设备的列表...然后尝试连接到每个设备(以确定是否已连接).
- 或者,您可以让后台服务监视Bluetooth API并将设备状态写入磁盘,以供您的应用程序以后使用.
这篇关于如何以编程方式判断是否已连接蓝牙设备?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文