安卓BLE蓝牙断开连接的两种方式

1.bluetoothGatt.disconnect()
使用disconnect()方法断开GATT连接时会触发BluetoothGattCallback中的onConnectionStateChange回调,onConnectionStateChange方法回调如下。

public void onConnectionStateChange(android.bluetooth.BluetoothGatt gatt, int status, int newState) 

其中newState为BluetoothProfile.STATE_CONNECTED时,表示有连接蓝牙GATT成功,BluetoothProfile.STATE_DISCONNECTED表示蓝牙断开连接,也就是当调用disconnect()方法方法时,会触发BluetoothProfile.STATE_DISCONNECTED,我们可以在触发BluetoothProfile.STATE_DISCONNECTED时,选择去释放资源,如bluetoothGatt.close()。

2.bluetoothGatt.close()
一但调用了该方法, 如果你想再次连接,必须调用BluetoothDevice的connectGatt()方法. 因为close()方法将释放BluetootheGatt的所有资源。需要注意的是,如果在disconnect后立即调用close,会导致无法回调onConnectionStateChange方法。

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 Android BLE 蓝牙连接代码示例: ``` private BluetoothManager bluetoothManager; private BluetoothAdapter bluetoothAdapter; private BluetoothDevice bluetoothDevice; private BluetoothGatt bluetoothGatt; // 初始化 BluetoothManager 和 BluetoothAdapter bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); bluetoothAdapter = bluetoothManager.getAdapter(); // 扫描设备并连接 bluetoothAdapter.startLeScan(new UUID[]{MY_UUID}, mLeScanCallback); bluetoothDevice.connectGatt(this, false, mGattCallback); // 扫描设备的回调函数 private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) { if (device.getAddress().equals(DEVICE_ADDRESS)) { bluetoothDevice = device; bluetoothAdapter.stopLeScan(mLeScanCallback); } } }; // 连接设备的回调函数 private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { if (newState == BluetoothProfile.STATE_CONNECTED) { bluetoothGatt = gatt; // 连接成功,开始发现服务 bluetoothGatt.discoverServices(); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { // 连接断开 bluetoothGatt.close(); } } @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { // 发现服务成功,可以开始进行操作 BluetoothGattService service = gatt.getService(SERVICE_UUID); BluetoothGattCharacteristic characteristic = service.getCharacteristic(CHARACTERISTIC_UUID); characteristic.setValue("Hello, BLE!"); gatt.writeCharacteristic(characteristic); } } @Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { // 写入特征值成功 } }; ``` 需要注意的是,此示例中的 UUID、DEVICE_ADDRESS、SERVICE_UUID 和 CHARACTERISTIC_UUID 都需要根据实际情况进行替换。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值