我寫一個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();
}
}
對我來說,它看起來並不像一個很好的使用情況'AsyncTask'。更像是運行在它自己的線程上的綁定服務。 – tynn
我是Android新手。 BLE通信作爲服務實施。在我的MainActivity,我實現了一個廣播接收器,其可以從BLE服務收到的消息,一旦收到了解析消息。在這種情況下,開始另一項服務會更好嗎? – eepty