How to update UI in a BroadcastReceiver

I suggest you use a Handler.

  1. Initialize a Handler in the Activity, example: handler = new Handler()
  2. Provide the handler to the BroadcastReceiver in the constructor, in the same way as I did for NissanTabBroadcast above
  3. Use post() method of your Handler instance in the onReceive() method to submit the Runnable that updates the UI

This is the cleanest solution I can imagine.

public class MainActivity extends Activity {

    private MyReceiver receiver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        receiver = new MyReceiver(new Handler()); // Create the receiver
        registerReceiver(receiver, new IntentFilter("some.action")); // Register receiver

        sendBroadcast(new Intent("some.action")); // Send an example Intent
    }

    public static class MyReceiver extends BroadcastReceiver {

        private final Handler handler; // Handler used to execute code on the UI thread

        public MyReceiver(Handler handler) {
            this.handler = handler;
        }

        @Override
        public void onReceive(final Context context, Intent intent) {
            // Post the UI updating code to our Handler
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(context, "Toast from broadcast receiver", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
}

Leave a Comment