该问题是由于Android 12中的BluetoothGatt缓存机制导致的。缓存导致它会将同一外设的多个服务和特征识别为同一服务和特征,从而导致连接中的冲突。解决这个问题,是通过在连接处清除缓存来实现的。
以下是一个示例代码,可以解决这个问题:
public class MyBluetoothGattCallback extends BluetoothGattCallback {
private BluetoothGatt mGatt;
public MyBluetoothGattCallback(BluetoothGatt gatt) {
mGatt = gatt;
}
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if(newState == BluetoothProfile.STATE_CONNECTED) {
gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH);
gatt.discoverServices();
clearGattCache(mGatt); //清除缓存
} else if(newState == BluetoothProfile.STATE_DISCONNECTED){
mGatt.close();
}
}
private void clearGattCache(BluetoothGatt gatt) {
try {
Method localMethod = gatt.getClass().getMethod("refresh");
if (localMethod != null) {
localMethod.invoke(gatt);
}
} catch (Exception localException) {
Log.e("ClearGattCache", "An exception occurred while refreshing device");
}
}
}
在MyBluetoothGattCallback中,当状态改变为STATE_CONNECTED时,我们清除蓝牙Gatt缓存。 这种方法可以有效地防止同一外设的多个服务和特征被识别为同一服务和特征。