我建议您在订阅特征时应设置 ENABLE_NOTIFICATION_VALUE。这是我执行此操作的代码:
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
List<BluetoothGattService> services = getSupportedGattServices();
for (BluetoothGattService service : services) {
if (!service.getUuid().equals(UUID_TARGET_SERVICE))
continue;
List<BluetoothGattCharacteristic> gattCharacteristics =
service.getCharacteristics();
// Loops through available Characteristics.
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
if (!gattCharacteristic.getUuid().equals(UUID_TARGET_CHARACTERISTIC))
continue;
final int charaProp = gattCharacteristic.getProperties();
if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
setCharacteristicNotification(gattCharacteristic, true);
} else {
Log.w(TAG, "Characteristic does not support notify");
}
}
}
} else {
Log.w(TAG, "onServicesDiscovered received: " + status);
}
}
然后您可以使用 NOTIFICATION 订阅特征:
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
boolean enabled) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID_DESCRIPTOR);
descriptor.setValue(enabled?BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
:BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
}
在此之后,您可以开始写入设备:
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
if (descriptor.getCharacteristic().getUuid().equals(UUID_TARGET_CHARACTERISTIC)) {
Log.i(TAG, "Successfully subscribed");
}
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);
} else {
Log.e(TAG, "Error subscribing");
}
}
并且您将收到onCharactersticChanged
读取的回调,无需实际调用读取操作。
请记住,mBluetoohGatt 一次只能处理 1 个操作,如果在前一个未完成的情况下执行另一个操作,它不会放入队列,但会返回 false。