androidbluetooth-lowenergyandroid-bluetoothbluetooth-gatt

Andoird [Bluetooth LE] create Characteristic with predefine value before advertising Service in a peripheral device(Android app)


My app act as a peripheral device advertising a Service with Characteristic with predefine value and the central device read it and process the advertising data

but I've been struggling with setting the value for a Characteristic in the Service when advertising

There's the setValue method on the BluetoothGattCharacteristic class but it's deprecated

Here's a snippet of my code


val rxCharacteristic = BluetoothGattCharacteristic(
    UUID.fromString("myuuid"),
    BluetoothGattCharacteristic.PROPERTY_READ,
    BluetoothGattCharacteristic.PERMISSION_READ
)
rxCharacteristic.setValue(payload)

The above code work but the Characteristic value is null and also the android studio shows me that the method is deprecated here's the documentation page for it:

https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic#setValue(java.lang.String)

As I said my use case is that the peripheral device (mobile app) set the value of the characteristic in advence and then the central device read it

I managed to implement that in iOS with CoreBluetooth


    let myChar1 = CBMutableCharacteristic(
    type: CBUUID(nsuuid: UUID(uuidString: "characteristicUuid")!), 
    properties: [.read],
    value: payload,
    permissions: [.readable])

Is it possible in Android as well or i'm doing it in a wrong way


Solution

  • without having more context of your code, I'm not sure if the answer will be sufficient but if you implement your own subclass of BluetoothGattServerCallback, you can then set the initial value as an attribute of your class and return it with BluetoothGattServer.sendResponse() when onCharacteristicReadRequest is being called.

    https://developer.android.com/reference/android/bluetooth/BluetoothGattServerCallback#onCharacteristicReadRequest(android.bluetooth.BluetoothDevice,%20int,%20int,%20android.bluetooth.BluetoothGattCharacteristic)