简体   繁体   English

Android BLE读取Gatt特性

[英]Android BLE read Gatt Characteristic

I am trying to read some Bluetooth Characteristics in my APP. 我正在尝试在我的APP中阅读一些蓝牙特性。 Now i have a Problem with what to do after the characteristic changed from my Gatt Server. 现在我对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). 但问题在于,似乎数据在某一时刻已损坏(例如我一直从MCU端将相同的数据写入特征)。

Is it allowed to read BLE data like this? 这样可以读取BLE数据吗? Is there any suggested way to read BLE data all the time? 有什么建议的方式可以一直读取BLE数据吗? Or update it on my App side? 还是在我的应用程序端进行更新?

If you Need any additional code, please let me know. 如果您需要任何其他代码,请告诉我。

Reading GATT characteristics is an asynchronous operation. 读取GATT特征是异步操作。 The result is not available until you receive the onCharacteristicRead callback. 在收到onCharacteristicRead回调之前,结果不可用。

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. 无论如何,您应该将GATT服务器配置为在有新数据要发送时发送通知 ,而不是一直轮询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM