What is the proper method for reading a GATT characteristic in Android?
Asked Answered
D

1

11

In attempting to read the value of a Bluetooth Low-Energy GATT characteristic in the Android API 18, I came across the following dilemma: What is the proper way to retrieve the value stored in a characteristic? And at which level of the stack should this action take place?

In conducting my own research, I stumbled upon what I understand are two possible methods:

  • BluetoothGatt.readCharacteristic(BluetoothGattCharacteristic characteristic)
  • BluetoothGattCharacteristic.getValue()

    public void onClick(View v){        
        byteValue = mBTValueCharacteristic.getValue();
        if ((byteValue[0] & 0x01) == 1)
            byteValue[0] = 0x00;
        else
            byteValue[0] = 0x01;
    
        mBTValueCharacteristic.setValue(byteValue);
        mBTGatt.writeCharacteristic(mBTValueCharacteristic);
    }
    

Above is the original code which led me to this issue. In it, I attempt to read the value of a characteristic, and simply toggle its state using a button.

Daye answered 16/11, 2013 at 2:57 Comment(0)
C
9
BluetoothGatt.readCharacteristic(BluetoothGattCharacteristic characteristic)

This function is updating your BluetoothGattCharacteristic object (on your Android device) using characteristic value from the Bluetooth .

BluetoothGattCharacteristic.getValue()

This function is just a getter function of the BluetoothGattCharacteristic object. There is not any transaction between android and the bluetooth device.

Cordwood answered 16/11, 2013 at 15:38 Comment(2)
Thank you for the clarification, but I have one more question then. Do you think I can both read the characteristic and obtain its value within the same click action? Will there be a timing issue due to the nature of the wireless connection?Daye
Wait until onCharacteristicRead callback fires, or else you are just getting the old value.Cordwood

© 2022 - 2024 — McMap. All rights reserved.