2016-09-13 41 views
0

我在MainActivity一個按鈕,用於寫入一byte[]到BLE設備:該程序是否正確寫入藍牙低能量特性?

<Button 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text="Write Char" 
    android:id="@+id/button2" 
    android:onClick="onClickWrite" /> 

和函數onClickWrite

public void onClickWrite(View v){ 
    if(mBluetoothLeService != null) { 
     byte [] data= new byte[3]; 
     data[0] = (byte)(0 & 0xFF); 
     data[1] = (byte)(255 & 0xFF); 
     data[2] = (byte)(0 & 0xFF); 
     mBluetoothLeService.sendData(data); 
    } 
} 

其中sendData[BluetoothLeService][1]類的改性功能。當我按下按鈕時,它運行良好。不過,讓我們仔細看看sendData函數。當我按下按鈕時,它再次搜索服務和特性。在BLE中寫入特性是否正確?

public void sendData(byte[] data){ 
    String lService = "00001c00-d102-11e1-9b23-00025b00a5A5"; 
    String lCharacteristic = "00001c03-d102-11e1-9b23-00025b00a5a5"; 
    BluetoothGattService mBluetoothLeService = null; 
    BluetoothGattCharacteristic mBluetoothGattCharacteristic = null; 

    for (BluetoothGattService service : mBluetoothGatt.getServices()) { 
     if ((service == null) || (service.getUuid() == null)) { 

      Log.d("TAG","Something is null"); 
      continue; 
     } 
     if (lService.equalsIgnoreCase(service.getUuid().toString())) { 

      Log.d("TAG","service.getUuid().toString()="+service.getUuid().toString()); 
      mBluetoothLeService = service; 
     } 
    } 
    if(mBluetoothLeService!=null) { 
     mBluetoothGattCharacteristic = 
       mBluetoothLeService.getCharacteristic(UUID.fromString(lRgbCharacteristic)); 
    } 
    else{ 
     Log.d("TAG","mBluetoothLeService is null"); 
    } 

    if(mBluetoothGattCharacteristic!=null) { 
     mBluetoothGattCharacteristic.setValue(data); 

     boolean write = mBluetoothGatt.writeCharacteristic(mBluetoothGattCharacteristic); 

     Log.d("TAG","writeCharacteristic:"+write); 
    } 
    else{ 
     Log.d("TAG", "mBluetoothGattCharacteristic is null"); 
    } 
} 
+0

不錯;但你也可以考慮一個處理程序來解析數據 –

回答

1

是的。

(填充不必要的長度)

+0

但是,當我單擊按鈕時,代碼重複查找並打開服務。我們是否有辦法打開一次 – Jame

+0

在發現服務之後只執行一次查找,將適當的服務分配給本地變量並刪除按鈕處理程序中的查找代碼。 –

+0

所以我的代碼就像你說的那樣正確。寫入BLE是正常的方法。 – Jame