How to update the UI of Activity from BroadCastReceiver

A BroadcastReceiver can be used in many ways but when it comes to something as specific as updating the UI components of an Activity, there is little advantage to declaring / defining a BroadcastReceiver in it’s own Java class file.

Reasoning – the BroadcastReceiver has to have some prior “knowledge” of the Activity and what it is required to do in order to update the UI. In effect the BroadcastReceiver is tied to the Activity itself and it makes sense to declare / define it as an inner class.

Another important aspect is the Activity needs to be in a “running” (i.e., visible) state in order to guarantee manipulation of UI components. In this case, registering the receiver in onResume() and unregistering in onPause() will help prevent problems.

Using a generic template I’d do something like the following…

class MyActivity extends Activity {

    boolean mIsReceiverRegistered = false;
    MyBroadcastReceiver mReceiver = null;

    // onCreate(...) here

    @Override
    protected void onResume() {

        // Other onResume() code here

        if (!mIsReceiverRegistered) {
            if (mReceiver == null)
                mReceiver = new MyBroadcastReceiver();
            registerReceiver(mReceiver, new IntentFilter("YourIntentAction"));
            mIsReceiverRegistered = true;
        }
    }

    @Override    
    protected void onPause() {
        if (mIsReceiverRegistered) {
            unregisterReceiver(mReceiver);
            mReceiver = null;
            mIsReceiverRegistered = false;
        }

        // Other onPause() code here

    }

    private void updateUI(Intent intent) {
        // Do what you need to do
    }

    private class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            updateUI(intent);
        }
    }
}

EDIT: A couple of extra notes…

  1. The life-cycle of a BroadcastReceiver is between entering and leaving onReceive(...). Once it has returned from onReceive(...) the instance remains in a dormant state waiting for the next broadcast.
  2. Directly related to point 1 – a BroadcastReceiver isn’t designed for “heavy lifting”. Basically the onReceive(...) method should be kept as simple as possible. Any methods it calls should also be as light-weight as possible…get in, do your stuff, get out then wait for the next broadcast. If updating the UI is going to take some time (perhaps updating a ListView by re-querying a database for a large amount of data for example), consider calling code which performs asynchronously (an AsyncTask for example).

Leave a Comment