2016-05-11 212 views
0

爲什麼它不起作用? 「#」正確發送但未讀取(其他設備讀取字符併發送)。我想我不能在同一時間執行以下兩個函數,但爲什麼?藍牙低功耗Android Studio

Read_Data.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      //Write 
      Data_BLE_Write("#"); 

      //Read 
      Data_BLE_Read(); 

      Toast.makeText(getApplicationContext(), "Data !!", Toast.LENGTH_SHORT).show(); 
     } 
    }); 

但是,如果我separe Data_Ble_Read和Data_Ble_Write有兩個按鈕,它的操作,所以我不明白爲什麼? 我的功能:

private void Data_BLE_Write(String Caract){ 
    if (mGattCharacteristics != null) { 
     final BluetoothGattCharacteristic characteristic_W = 
       mGattCharacteristics.get(3).get(1); 
     final int charaProp = characteristic_W.getProperties(); 

     if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) { 
      mNotifyCharacteristic = characteristic_W; 
      mBluetoothLeService.setCharacteristicNotification(
        characteristic_W, true); 
     } 
     if ((charaProp | BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) { 
      String str = Caract; 
      byte[] strBytes = str.getBytes(); 
      characteristic_W.setValue(strBytes); 
      mBluetoothLeService.writeCaracteristic(characteristic_W); 
     } 
    } 
} 
    private String Data_BLE_Read(){ 
    Data_Read_Ble = ""; 
    if (mGattCharacteristics != null) { 
     final BluetoothGattCharacteristic characteristic = 
       mGattCharacteristics.get(2).get(6); 
     final int charaProp = characteristic.getProperties(); 
     if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) { 
      // If there is an active notification on a characteristic, clear 
      // it first so it doesn't update the data field on the user interface. 
      if (mNotifyCharacteristic != null) { 
       mBluetoothLeService.setCharacteristicNotification(
         mNotifyCharacteristic, false); 
       mNotifyCharacteristic = null; 
      } 
      mBluetoothLeService.readCharacteristic(characteristic); 
     } 
     if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) { 
      mNotifyCharacteristic = characteristic; 
      mBluetoothLeService.setCharacteristicNotification(
        characteristic, true); 
     } 
     Data_BLE_Write("&"); 
    } 
    return Data_Read_Ble; 
} 
+0

「但是,如果我用兩個按鈕分開Data_Ble_Read和Data_Ble_Write,它就會運行,所以我不明白爲什麼? < - 可能是因爲寫入和讀取之間存在足夠的延遲。當它們在同一按鈕下時,讀取在寫入之後立即發生。 –

回答

1

的BLE堆棧允許在同一時間只有一個任務,所以基本上你放棄你的讀取任務寫入任務。您應該等待下一個任務,直到之前的任務完成爲止,在這種情況下,您應該等到該屬性被讀取後再開始寫入。

希望這會有所幫助。