In some Android phones, when connecting to the GATTService directly requestMtu may cause the Bluetooth connection is interrupted, and then continue to reconnect will report an error Need BLUETOOTH PRIVILEGED permission.
1 //Connecting to gatt after a successful scan 2 BluetoothDevice mRemoteDevice = (().getAddress()); 3 BluetoothGatt mBluetoothGatt = (getContext(), false, bluetoothGattCallback);
Directly requestMtu(512) in the onConnectionStateChange(BluetoothGatt gatt, int status, int newState) method of the BluetoothGattCallback listener will result in a direct Bluetooth disconnection.
1 private int setMTUInt = 512; 2 3 4 @Override 5 public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { 6 (gatt, status, newState); 7 8 if (newState == BluetoothProfile.STATE_CONNECTED) { //// Connection successful 9 //Although the boolean here will be true it will actually fail and cause the Bluetooth to disconnect 10 boolean requestMtu = (setMTUInt); 11 (TAG,"Sets the requestMtu:"+requestMtu); 12 13 } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { // disconnection 14 //Clear the cache to prevent Need BLUETOOTH PRIVILEGED permission. 15 refreshDeviceCache(); 16 //Decrease the MTU value, the value can be set freely. 17 setMTUInt -= 100; 18 // Close the GATT client 19 (); 20 } 21 }
In the listening onMtuChanged(BluetoothGatt gatt, int mtu, int status) method, confirm that the mtu is set successfully and then request the feature value
1 @Override 2 public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) { 3 (gatt, mtu, status); 4 5 // Start looking for services provided by the GATT server 6 (); 7 8 }
The characteristics are then set in the listening onServicesDiscovered(BluetoothGatt gatt, int status) method
@Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { (gatt, status); if (status == BluetoothGatt.GATT_SUCCESS) { //Setting the eigenvalues requestCharacteristic(); } }
To clear the cache, gatt itself provides a method to clear the cache, but it is not called directly from the outside, so it is called using reflection. It is recommended to clear the cache every time you turn on the scanning device, to prevent linking to a new device after linking to another device from reporting an error : Need BLUETOOTH PRIVILEGED permission: Neither user 10208 nor current process has .BLUETOOTH_PRIVILEGED.
1 public boolean refreshDeviceCache() { 2 if (mBluetoothGatt != null) { 3 (TAG,"Clear the cache refreshDeviceCache"); 4 try { 5 BluetoothGatt localBluetoothGatt = mBluetoothGatt; 6 Method localMethod = ().getMethod( 7 "refresh", new Class[0]); 8 if (localMethod != null) { 9 boolean bool = ((Boolean) ( 10 localBluetoothGatt, new Object[0])).booleanValue(); 11 return bool; 12 } 13 } catch (Exception localException) { 14 (TAG, "An exception occured while refreshing device"); 15 } 16 } 17 return false; 18 }