如何以编程方式判断蓝牙设备是否已连接?我知道如何获得成对设备的列表,但如何判断它们是否相连?这必须是可能的,因为我看到他们列在我的手机的蓝牙设备列表,并说明他们的连接状态。
3 回答
墨色风雨
TA贡献1853条经验 获得超6个赞
<uses-permission android:name="android.permission.BLUETOOTH" />
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 broadcastsprivate 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,并将设备状态写入磁盘,以便应用程序稍后使用。
紫衣仙女
TA贡献1839条经验 获得超15个赞
public static boolean isBluetoothHeadsetConnected() { BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); return mBluetoothAdapter != null && mBluetoothAdapter.isEnabled() && mBluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothHeadset.STATE_CONNECTED;}
<uses-permission android:name="android.permission.BLUETOOTH" />
- 3 回答
- 0 关注
- 570 浏览
添加回答
举报
0/150
提交
取消