在Arduino端,使用以下代码设置BLE特征通知:
BLEDescriptor desc(UUID16_SDESC_NOTIFY_CHAR);
characteristic.addDescriptor(desc);
characteristic.notify(true);
在Android端,使用以下代码设置BLE特征通知:
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(CLIENT_CHARACTERISTIC_CONFIG));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
如果仍然无法响应onCharacteristicChanged回调,则可以尝试在Android端将writeType设置为WRITE_TYPE_DEFAULT:
mBluetoothGatt.setCharacteristicWriteType(characteristic, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
此外,还可以尝试在Android端将特征读取、写入、通知的超时时间分别增加:
mBluetoothGatt.readCharacteristic(characteristic).setTimeout(5000);
mBluetoothGatt.writeCharacteristic(characteristic).setTimeout(5000);
mBluetoothGatt.setCharacteristicNotification(characteristic, true).setTimeout(5000);