Android应用编程实现蓝牙设备连接与非配对式断开
如何在保留配对的前提下断开Android蓝牙设备连接
首先要明确:**配对(Bonded)是设备间保存信任凭证的状态,而连接(Connected)**是当前建立的通信链路。removeBond()是删除配对关系(对应系统设置的「忘记设备」),而你需要的是仅断开当前连接、保留配对,核心是关闭通信链路而非删除配对信息。
核心实现思路
断开连接的关键是关闭已建立的蓝牙通信通道,具体分两种设备类型处理:
1. 经典蓝牙设备(传统蓝牙,如耳机、蓝牙串口设备)
配对后建立连接时,你肯定创建并保存了BluetoothSocket实例,断开时直接关闭这个socket即可:
// 假设已保存连接成功的BluetoothSocket对象 private BluetoothSocket mConnectedSocket; // 断开连接方法,必须在子线程执行(避免UI线程ANR) public void disconnectClassicDevice() { if (mConnectedSocket != null && mConnectedSocket.isConnected()) { try { mConnectedSocket.close(); mConnectedSocket = null; // 释放资源 } catch (IOException e) { // 处理断开失败的异常,比如打印日志 e.printStackTrace(); } } } // 重新连接(无需重新配对) public void reconnectClassicDevice(BluetoothDevice targetDevice, UUID serviceUuid) { new Thread(() -> { try { // 利用已配对的设备直接创建socket BluetoothSocket socket = targetDevice.createRfcommSocketToServiceRecord(serviceUuid); socket.connect(); mConnectedSocket = socket; // 连接成功后可继续获取输入输出流进行通信 } catch (IOException e) { e.printStackTrace(); } }).start(); }
2. BLE蓝牙设备(低功耗蓝牙,如智能手环)
BLE设备通过BluetoothGatt管理连接,断开时先调用disconnect()再close():
// 假设已保存连接的BluetoothGatt对象 private BluetoothGatt mBluetoothGatt; // 断开BLE连接 public void disconnectBleDevice() { if (mBluetoothGatt != null) { mBluetoothGatt.disconnect(); mBluetoothGatt.close(); mBluetoothGatt = null; } } // 重新连接BLE设备(无需配对) public void reconnectBleDevice(BluetoothDevice targetDevice, Context context) { // 第二个参数为false表示不自动连接,按需调整 mBluetoothGatt = targetDevice.connectGatt(context, false, mGattCallback); }
注意事项
- 权限要求:Android 12及以上需要申请
BLUETOOTH_CONNECT权限,低版本需要BLUETOOTH和BLUETOOTH_ADMIN权限,且要动态申请危险权限。 - 断开后可监听系统广播
BluetoothDevice.ACTION_ACL_DISCONNECTED,确认设备已成功断开。 - 保存的配对设备列表可通过
BluetoothAdapter.getBondedDevices()获取,这些设备无需重新配对即可直接尝试连接。
内容的提问来源于stack exchange,提问作者J L U
相关产品推荐
相关产品推荐

