user3678020 user3678020 - 1 month ago 12
Android Question

BluetoothGatt.writeCharacteristic() always returns false.

I am writing an Android app to talk with an Arduino using BLE. I have been able to scan devices, connect to the target, discover services, get characteristics, and read those that are readable. However, when I try to write a writeable characteristics, the method always returns false. When I debugged into the android.bluetooth code, the following sequence occurs:
characteristic.getService().getDevice always returns null,
which causes the writeCharacteristic to fail.

Any help is greatly appreciated!

Answer

Please check your objects in the corresponding sequence. I keep only the BluetoothGatt object and create BluetoothGattService and BluetoothGattCharacteristic every time I need to write to the BLE device.

byte[] data_to_write; // Your data
BluetoothManager mBluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SREVICE);
BluetoothAdapter mBluetoothAdapter = mBluetoothManager.getAdapter();
BluetoothDevice mDevice = mBluetoothAdapter.getRemoteDevice(....);
BluetoothGatt mBG = mDevice.connectGatt(....);

BluetoothGattService mSVC = mBG.getService(service_uuid);
BluetoothGattCharacteristic mCH = mSVC.getCharacteristic(characteristic_uuid);
mCH.setValue(data_to_write);
mBG.writeCharacteristic(mCH);