gpt4 book ai didi

android - 如何以编程方式判断蓝牙设备是否已连接?

转载 作者:IT老高 更新时间:2023-10-28 13:11:40 27 4
gpt4 key购买 nike

我了解如何获取已配对设备的列表,但如何判断它们是否已连接?

这一定是可能的,因为我看到它们列在我手机的蓝牙设备列表中,并说明了它们的连接状态。

最佳答案

将蓝牙权限添加到您的 AndroidManifest,

<uses-permission android:name="android.permission.BLUETOOTH" />

然后使用 Intent 过滤器监听 ACTION_ACL_CONNECTEDACTION_ACL_DISCONNECT_REQUESTEDACTION_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 - 如何以编程方式判断蓝牙设备是否已连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4715865/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com