I am writing an Android app to talk with an BLE meter. I have been able to scan devices, connect to the target, discover services, get characteristics. However, when I try to write a write_no_reponse characteristics the method always returns false. I am sure the characteristics is writeable, i use others app do it. When I debugged into the android.bluetooth code, the following sequence occurs failure, maybe it return a null service, debug run to this step and then step out the method:
BluetoothGattService service = characteristic.getService();
which causes the writeCharacteristic return false. But before writeCharacteristic, I have a log
Log.d(TAG, "onServicesDiscovered: writeType" + mCharacteristic.getService());
bluetoothGatt.writeCharacteristic(mCharacteristic);
and the log is correct and does not return null;
Any help is greatly appreciated!
And I use the same code to write to a WRITE characteristics, it worked. And I try use the
mCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
to set the write type, but it also failed.
the write data code:
public void writeReadDataCommand() {
if (null != bluetoothGatt) {
mCharacteristic.setValue("123123");
bluetoothGatt.setCharacteristicNotification(mCharacteristic, true);
mCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
Log.d(TAG, "onServicesDiscovered: writeType" + mCharacteristic.getService());
boolean isWrite = bluetoothGatt.writeCharacteristic(mCharacteristic);
if (isWrite) {
Log.d(TAG, "writeReadDataCommand: write data to BLE");
}
}
}
the onServiceDiscovered code:
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
bluetoothGatt = gatt;
BluetoothGattService service = gatt.getService(UUID.fromString(SERVICE_UUID));
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(CHARACTERISTIC_UUID));
Log.d(TAG, "onServicesDiscovered: writeType" + characteristic.getWriteType());
boolean isSuccess = gatt.setCharacteristicNotification(characteristic, true);
if (isSuccess) {
mCharacteristic = characteristic;
List<BluetoothGattDescriptor> descriptors = characteristic.getDescriptors();
if (null != descriptors && descriptors.size() > 0) {
for (BluetoothGattDescriptor descriptor : descriptors) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
gatt.writeDescriptor(descriptor);
}
}
}
connectCallback.findService();
} else {
Log.d(TAG, "onServicesDiscovered received: " + status);
}
}
and the onCharacteristicWrite callback does not trigger
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
Log.d(TAG, "onCharacteristicWrite: " + Arrays.toString(characteristic.getValue()));
}
I have this bug for a long time, thanks so much if someone could help.