Android:如何在AsyncTask中实现“等待接收数据”

时间:2016-06-28 02:16:19

标签: android android-asynctask

我正在编写一个Android应用程序,它将通过BLE(蓝牙低功耗)向另一台设备发送消息,设备将响应ACK / NACK消息。我使用的BLE服务将使通信行为像普通的UART通信一样。

我在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();
    }
}

2 个答案:

答案 0 :(得分:0)

以某种方式提出问题Set timeout function with AsyncTask [Android]

你应该在doInBackground中实现取消机制并通过超时调用AsyncTask.cancel()[像那样](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);

在你的情况下,你考虑过服务吗?

答案 1 :(得分: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);
}