在Android 6.0且API Level低于24。部分手机会无法接收到onCharacteristicChanged()所返回的消息,使用以下方法能够完美解决问题。
public boolean enableNotification(BluetoothGatt gatt, UUID serviceUUID, UUID characteristicUUID) {
// BluetoothGattService service = gatt.getService(serviceUUID);
// BluetoothGattCharacteristic characteristic = findNotifyCharacteristic(service, characteristicUUID);
// if (characteristic != null) {
// if(bluetoothGatt.setCharacteristicNotification(characteristic2, true)){
// //获取到Notify当中的Descriptor通道 然后再进行注册
// BluetoothGattDescriptor clientConfig = characteristic2 .getDescriptor(UUID.fromString(DESCRIPTOR_UUID));
// clientConfig.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
// bluetoothGatt.writeDescriptor(clientConfig);
// }
boolean success = false;
BluetoothGattService service = gatt.getService(serviceUUID);
if (service != null) {
BluetoothGattCharacteristic characteristic = findNotifyCharacteristic(service, characteristicUUID);
if (characteristic != null) {
success = gatt.setCharacteristicNotification(characteristic, true);
gatt.readCharacteristic(characteristic);
if (success) {
for(BluetoothGattDescriptor dp: characteristic.getDescriptors()){
if (dp != null) {
if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
dp.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
} else if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0) {
dp.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
}
int writeType = characteristic.getWriteType();
Log.e(TAG, "enableNotification: "+writeType ); characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
bluetoothGatt.writeDescriptor(dp);
characteristic.setWriteType(writeType);
}
}
}
}
}
return success;
}
private BluetoothGattCharacteristic findNotifyCharacteristic(BluetoothGattService service, UUID characteristicUUID) {
BluetoothGattCharacteristic characteristic = null;
List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
for (BluetoothGattCharacteristic c : characteristics) {
if ((c.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0 && characteristicUUID.equals(c.getUuid())) {
characteristic = c;
break;
}
}
if (characteristic != null) {
return characteristic;
}
for (BluetoothGattCharacteristic c : characteristics) {
if ((c.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0 && characteristicUUID.equals(c.getUuid())) {
characteristic = c;
break;
}
}
return characteristic;
}
然后只需在onServicesDiscovered()方法中调用这个方法即可
enableNotification(bluetoothGatt,serviceNotifyUUID, notifyUUID);
serviceNotifyUUID为服务ID,notifyUUID为notify的UUID