2016-06-28 27 views
1

我寫一個Android應用程序,它會通過BLE(低功耗藍牙)將消息發送到另一臺設備,並且該設備將響應一個ACK/NACK信息。我使用的BLE服務將使通信像普通的UART通信一樣工作。安卓:如何實現「等待接收數據」中的AsyncTask

我實現了一個的AsyncTask兩個設備之間的通信,因爲通信涉及多個發送/接收循環。我可以發送消息和接收消息,該問題是,我發送的消息後,我需要等待至少一段時間(超時),以接收響應。在這段等待時間內,我需要檢查我是否重複收到有效的回覆,並且在超時之後,我需要停止等待。我知道我們可以讓AsyncTask進入睡眠狀態,所以睡眠時間就是超時。然而,我只能在完整的睡眠時間後才能檢查消息,比如3s,效率不高。

如何做到這一點?

下面是我的AsyncTask:

public class configTask extends AsyncTask<String, Integer, Integer> { 
    @Override 
    protected Integer doInBackground(String... message) { 

     // Using StringBuilder here just to show the example, 
     // I will add more string here in real situation 
     final StringBuilder sb = new StringBuilder(20); 
     sb.append("A test message\r"); 
     sb.trimToSize(); 
     try { 
      byte[] tx_data = String.valueOf(sb).getBytes("UTF-8"); 

      // This line will send out the packet through a BLE serivce, 
      // "mService" is the BLE service that I have initialize in the 
      // MainActivity. 
      mService.writeRXCharacteristic(tx_data); 
     } 
     catch (UnsupportedEncodingException e){ 
      Log.d(TAG, "Encode StringBuilder to byte[] get UnsupportedEncodingException"); 
     } 

     // After sent out the packet, I need to check whether received 
     // a valid response here. The receive and parse routine is 
     // implemented in the MainActivity, once the BLE service received a 
     // packet, it will parse it and set a flag to indicate a packet 
     // is received. 

     // And then other send/receive routines... 

     return null; 
    } 

    @Override 
    protected void onProgressUpdate(Integer... values) { 
     super.onProgressUpdate(values); 
    } 

    @Override 
    protected void onPostExecute(Integer result) { 
     super.onPostExecute(result); 
    } 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
    } 
} 
+0

對我來說,它看起來並不像一個很好的使用情況'AsyncTask'。更像是運行在它自己的線程上的綁定服務。 – tynn

+0

我是Android新手。 BLE通信作爲服務實施。在我的MainActivity,我實現了一個廣播接收器,其可以從BLE服務收到的消息,一旦收到了解析消息。在這種情況下,開始另一項服務會更好嗎? – eepty

回答

0

問題以某種方式同Set timeout function with AsyncTask [Android]

你應該落實超時[類似](https://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable, long))

final Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() { 
     @Override 
     public void run() { 
     AsyncTask.cancel(); 
     } 
    }, 1); 

在你的情況下取消力學doInBackground和調用AsyncTask.cancel()你認爲一個服務?

+0

但我不希望只是執行超時,我需要檢查是否在等待時間接收到BLE消息。你的代碼似乎只是在1ms後取消AsyncTask。 – eepty

+0

我演示瞭如何實現超時(看門狗),結果應該在'doInBackground()'中檢查,並且當你收到'onPostExecute()'時執行。仍然考慮使用服務。 –

0

你可以這樣做以下

numBytes = 0; 
for(int i=0; i<300; i++){ 
    numBytes += mService.read(bytes, .....) //Not sure about signature of your read method so just putting variables generally used. 

    //TODO - copy your bytes to main buffer here 

    if(numBytes == requiredBytes) 
     break 
    else 
     Thread.Sleep(10); 
}