每次写入时,Characteristic 的值都会更新,这就是为什么当您读取时,它只反映最新的值(您写入的最后一个值)。
要连续读取数据,您应该首先启用有关特征的通知。
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID_DESCRIPTOR);
descriptor.setValue(enabled?BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
:BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
然后就可以开始写数据了
byte[] data = <Your data here>;
BluetoothGattService Service = mBluetoothGatt.getService(UUID_TARGET_SERVICE);
BluetoothGattCharacteristic charac = Service
.getCharacteristic(UUID_TARGET_CHARACTERISTIC);
charac.setValue(data);
mBluetoothGatt.writeCharacteristic(charac);
现在每次编写时,客户端都会收到一个onCharactersticChanged
包含新更新值(data
)的回调。您实际上不需要调用读取操作。
请记住,mBluetoothGatt 一次只能处理 1 个操作,如果在前一个未完成的情况下执行另一个操作,它不会放入队列,但会返回 false。