Этот код включает уведомления по заданной характеристике:
Код: Выделить всё
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
boolean enabled) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(CLASS_NAME, "BluetoothAdapter not initialized");
return;
}
// Check if this characteristic actually has NOTIFY property
if((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) == 0 ) {
Log.e(CLASS_NAME, "Characteristic does not support notifications");
return;
}
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
// For characteristics that support it, write to the CCC descriptor
// that notifications are enabled.
if (enabled) {
if (TX_PERIPHERAL_TO_CENTRAL.equals(characteristic.getUuid())) {
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString(GattAttributes.TX_PERIPHERAL_TO_CENTRAL_CCC));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
if (!mBluetoothGatt.writeDescriptor(descriptor)) {
Log.d(CLASS_NAME, "Write to descriptor failed: "+TX_PERIPHERAL_TO_CENTRAL_CCC);
}
}
}
}
Вот код обратных вызовов:
Код: Выделить всё
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
Log.d(CLASS_NAME, "in onCharacteristicChange() characteristic = "+characteristic.getUuid());
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
super.onDescriptorWrite(gatt, descriptor, status);
Log.d(CLASS_NAME, "in onDescriptorWrite() status = "+status+", descriptor = "+descriptor.getUuid());
Log.d(CLASS_NAME, " descriptor value = "+descriptor.getValue());
}
Похожая проблема возникает с характеристическими записями. Вот код, который выполняет запись, но после этого onCharacteristicWrite никогда не вызывается:
Код: Выделить всё
public boolean writeCharacteristic(BluetoothGattCharacteristic characteristic, String data) {
boolean result = false;
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(CLASS_NAME, "BluetoothAdapter not initialized");
return false;
}
// Check if this characteristic actually has WRITE property
if((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE) == 0 ) {
Log.e(CLASS_NAME, "Characteristic is not writeable");
return false;
}
byte[] ascii = data.getBytes(StandardCharsets.US_ASCII);
if (characteristic.setValue(ascii)) {
result = mBluetoothGatt.writeCharacteristic(characteristic);
}
return result;
}
У меня также есть использовал BLE Scanner, чтобы убедиться, что характеристики, которые я использую, можно успешно записывать и читать с помощью уведомлений, так что, какова бы ни была проблема, она на моей стороне. И извините за беспорядочный код — он явно не завершен.
Подробнее здесь: https://stackoverflow.com/questions/725 ... cread-none