在Android 12中,当应用程序关闭时,系统不会自动断开蓝牙低功耗(Bluetooth LE)连接。这可能会产生一些负面影响,例如浪费电池寿命、占用带宽等。
为了解决此问题,可以使用新的Bluetooth GATT连接API。使用此API,应用程序可以请求系统在特定条件下保持连接。以下是一个示例代码,演示如何保持蓝牙低功耗连接:
private BluetoothGatt mBluetoothGatt;
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
// 省略其他回调方法
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
if (newState == BluetoothProfile.STATE_CONNECTED) {
Log.d(TAG, "Connected to GATT server.");
gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH);
gatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.d(TAG, "Disconnected from GATT server.");
mBluetoothGatt.close();
mBluetoothGatt = null;
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
BluetoothGattService service = gatt.getService(SERVICE_UUID);
BluetoothGattCharacteristic characteristic = service.getCharacteristic(CHARACTERISTIC_UUID);
gatt.setCharacteristicNotification(characteristic, true);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_UUID);
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
gatt.writeDescriptor(descriptor);
// Request to keep the connection open even when app is closed
BluetoothGattDescriptor keepAliveDescriptor = characteristic.getDescriptor(KEEP_ALIVE_UUID);
keepAliveDescriptor.setValue(KEEP_ALIVE_VALUE);
gatt.writeDescriptor(keepAliveDescriptor);
}