实现自动重连功能需要使用BluetoothGattCallback回调中的onConnectionStateChange方法。当BluetoothGatt.STATE_DISCONNECTED状态转换成BluetoothGatt.STATE_CONNECTED状态时,重新连接已配对的设备。
示例代码如下:
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { if (newState == BluetoothProfile.STATE_CONNECTED) { gatt.discoverServices(); // 连接成功后需要调用discoverServices扫描服务 } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { // 断开连接后尝试重连 mBluetoothGatt.connect(); } }
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
// 连接成功后的操作
} else {
// 连接失败后的操作
}
}
};
private void autoConnect() { // 进行自动连接 if (mBluetoothGatt != null) { mBluetoothGatt.disconnect(); mBluetoothGatt.close(); mBluetoothGatt = null; } BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(deviceAddress); mBluetoothGatt = device.connectGatt(this, false, mGattCallback); }
在设备断开连接后,可以调用autoConnect函数进行自动重连。这样就可以实现Android BLE在配对后的自动重连功能。