如果在搜索完服务后,执行多个 setCharacteristicNotification 或 writeCharacteristic 操作,某些操作可能会无效。需要在中间等待一些时间,真是一个大坑!
new Thread(new Runnable() {
@Override
public void run() {
try {
for (BluetoothGattService gattService : mBluetoothLeService.getSupportedGattServices()) {
List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
if (gattCharacteristic.getUuid().toString().equals("0000XXXX-0000-XXXX-XXXX-00XXXXXXXXXX")) {
Thread.sleep(150);
mgattCharacteristic = gattCharacteristic;
byte[] value = new byte[7];
/*
value = ......
*/
mgattCharacteristic.setValue(value);
mBluetoothLeService.writeCharacteristic(mgattCharacteristic);
}
if (gattCharacteristic.getUuid().toString().equals("0000XXXX-0000-XXXX-XXXX-00XXXXXXXXXX")){
Thread.sleep(150);
mBluetoothLeService.setCharacteristicNotification(gattCharacteristic, true);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();