如何以编程方式判断蓝牙设备是否已连接? [英] How can I 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 the 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 不允许您查询,而是允许您收听更改.
- 上述问题的一个变态解决方法是检索所有已知/配对设备的列表...然后尝试连接到每个设备(以确定您是否已连接).
- 或者,您可以让后台服务监视蓝牙 API 并将设备状态写入磁盘以供您的应用程序日后使用.
这篇关于如何以编程方式判断蓝牙设备是否已连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文