问题
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!
回答1:
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);
回答2:
Some characterictics are just not writeable. The code above should use some side effect. (not the same characterictics or ...)
来源:https://stackoverflow.com/questions/23879869/bluetoothgatt-writecharacteristic-always-returns-false