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

安卓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方法。

相关数据