Search code examples
androidbroadcastreceiver

How to wait for onReceive to finish while in same thread?


I have a BroadcastReceiver registered in the UI thread that grabs some information from the Bundle in its onReceive method. I need these values before I proceed in my main thread.

Is there any way to wait for the onReceive to finish before trying to use those values? I am running into timing issues where onReceive sets the values AFTER I try to use them. Having the thread sleep doesn't work, since they're on the same thread.

Would it make sense to register the receiver in an AsyncTask, and call wait() on the main thread, then have onReceive notify() once it completes?

String a = "hi";
IntentFilter filter = new IntentFilter();
filter.addAction(MY_CUSTOM_INTENT);
BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Set the variable values here
        a = "bye";
    }
};
getApplicationContext().registerReceiver(receiver, filter);

// Get the values, I am getting a = "hi" here because the onReceive code has 
// not been reached yet
// How can I guarantee that a = "bye" from this method?
getA();

where method is something like

String getA() {
    return a;
}

Solution

  • You seem to be over-complicating things. It's hard to know what you're really after based on the example code, but the code that comes after registerReceiver() should just do whatever else it needs to do and then return, without waiting for or hoping for the Broadcast to have been received. onReceive() should include whatever code you want to have executed at that point (which may well just be a method call, e.g. updateA("bye").