title: How to make an Android class wait until another class completes its task?
body: <p>I'm writing an Android messaging application, and 1 class is calling another class, and I wish for the calling class to wait for the callee class to complete before carrying on.</p>
  
  <p>Caller Class (MessageManagement) code snippet is as follows:</p>
  
  <pre><code>private static Messenger myMessenger;
  
  try {
    Message msg = Message.obtain();
    msg.arg1 = constructedMessage.length();
    msg.arg2 = -1;
    msg.obj = constructedMessage;
    Log.d(TAG, "Calling myMessenger.send()");
    myMessenger.send(msg);
    Log.d(TAG, "Sent");
  } catch (Exception e) {
    e.printStackTrace();
  }
  // Wait here until myMessenger completes its task
  doOtherStuff();
  </code></pre>
  
  <p>Right now, doOtherStuff() starts and finishes before myMessenger starts. I need myMessenger to complete before doOtherStuff() starts.</p>
  
  <p>I've read about wait() and notify() but I'm not sure how to implement it here, or whether it's the right choice.</p>
  
  <p>Some background about the flow of the program. It's basically a messaging app that I inherited, so I'm not exactly sure of its framework. From what I can tell tracing the flow of the code:</p>
  
  <ol>
  <li>When an SMS message is received, the SMS receiver BroadcastReceiver(SmsReceiver) handles it, getting the sender address and message body, then calling a SMS handler service(HandleSmsService), which then calls the caller class in a runnable with the following code:</li>
  </ol>
  
  <p>HandleSmsService</p>
  
  <pre><code>public class HandleSmsService extends Service {
    private String message;
    private MessageManagement messageManager;
    private Handler timeoutHandler = new Handler();
  
    @Override
    public void onStart(Intent intent, intent startid) {
      message = intent.getExtras().getString("message");
      messageManager = new MessageManagement(this);
      timeoutHandler.postDelayed(runnable, 10);
    }
  
    private Runnable runnable = new Runnable() {
      @Override
      public void run() {
        try {
          messageManager.handleMessage(message);
          stopSelf();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    };
  </code></pre>
  
  <p>MessageManagement is my caller class, and MessageManagement.handleMessage() is the top most code snippet presented earlier.</p>
  
  <p>The MessageManagement.handleMessage() apparently calls another Handler in the callee class when it calls myMessenger.send(msg). This Handler code is as follows:</p>
  
  <pre><code>private Handler smsHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      // do some stuff
    }
  };
  </code></pre>