B. Ben
B. Ben

Reputation: 109

Android BLE read Gatt Characteristic

I am trying to read some Bluetooth Characteristics in my APP. Now i have a Problem with what to do after the characteristic changed from my Gatt Server. At first i've tried to use a thread to retrigger the read for the characteristic again and again like this:

new Thread(new Runnable() {
    @Override
    public void run() {
        int[] newData = new int[30];
        while(true){
            try{
                for(int i=0;i<newData.length;i++){
                    newData[i] = 0;
                }
                BluetoothGatt tmpGatt = refExtDataClass.getRefBluetoothGatt();
                tmpGatt.readCharacteristic(characteristic);

                byte[] value = characteristic.getValue();

                for(int i=0;i<newData.length;i++){
                    newData[i] = value[i];
                }
                refExtDataClass.setNmData(newData);
            }catch(Exception e){
                break;
            }
        }
    }
}).start();

But the Problem is that it's seems like the data is corrupt at one point (like i've always writing the same data into the characteristic from my MCU side).

Is it allowed to read BLE data like this? Is there any suggested way to read BLE data all the time? Or update it on my App side?

If you Need any additional code, please let me know.

Upvotes: 2

Views: 5359

Answers (1)

Emil
Emil

Reputation: 18442

Reading GATT characteristics is an asynchronous operation. The result is not available until you receive the onCharacteristicRead callback.

Anyway, you should rather configure your GATT server to send notifications when it has new data to send rather than polling it all the time.

Upvotes: 2

Related Questions