2016-09-28 49 views
0

我正尝试在我的APP中阅读一些蓝牙特性。 现在我遇到了一个问题,即在从我的GATT服务器更改特性后应该如何处理。起初,我试图使用一个线程来一次又一次地重新触发该特性的这样写的:Android BLE阅读GAT特性

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(); 

但问题是,它似乎像数据被损坏的一个点(像我总是将相同的数据写入我的MCU端的特性中)。

是否允许像这样读取BLE数据?有没有建议的方式来读取BLE数据?或者在我的应用程序端更新它?

如果您需要任何额外的代码,请让我知道。

回答

1

阅读GATT特性是一种异步操作。在收到onCharacteristicRead回调之前,结果不可用。

无论如何,您应该配置您的GATT服务器,以便在发送新数据时发送notifications,而不是始终轮询它。

+0

很高兴听到有另一种方式我根本不喜欢我的“解决方案”。我刚刚读到,我需要“激活”来自我的gatt客户端的通知。如果我使用的是characteristic.addDescriptor(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE),那就足够了吗? –

+0

请参阅https://developer.android.com/guide/topics/connectivity/bluetooth-le.html#notification上的示例 – Emil