title: Android: How to implement a "wait for receiving data" in AsyncTask
body: <p>I am writing an Android App that it will send a message through BLE (Bluetooth Low Energy) to another device, and the device will response a ACK/NACK message. The BLE service that I use will make the communication act like a normal UART communication.</p>
  
  <p>I implemented the communication between the two devices in a AsyncTask, because the communication involve many send/receive loops. I can send the message and receive the message, the problem is that after I sent the message, I need to wait at least a period of time (a timeout) to receive the response. During this waiting time, I need to check if I received the valid response repeatedly, and after the timeout, I need to stop the waiting. I know we can make the AsyncTask sleep, so the sleep time is the timeout. However it would be not efficient that I can only check the message after a full sleep time, such as 3s.</p>
  
  <p>How to do that?</p>
  
  <p>Below is my AsyncTask:</p>
  
  <pre><code>public class configTask extends AsyncTask&lt;String, Integer, Integer&gt; {
      @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();
      }
  }
  </code></pre>