Example of a LocalBroadcastManager

suggest change

A BroadcastReceiver is basically a mechanism to relay Intents through the OS to perform specific actions. A classic definition being

“A Broadcast receiver is an Android component which allows you to register for system or application events.”

LocalBroadcastManager sends and receives broadcasts inside one application process.

  1. The broadcast stays in the application process.
  2. Delivery stays in-process, so the system does not resolve the Intent across the device.

A simple example of a LocalBroadcastManager:

SenderActivity

Intent intent = new Intent("anEvent");
intent.putExtra("key", "This is an event");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

ReceiverActivity

Register the receiver:

LocalBroadcastManager.getInstance(this).registerReceiver(aLBReceiver, new IntentFilter("anEvent"));

The receiver:

private BroadcastReceiver aLBReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // perform action here.
    }
};

Unregister when the activity is no longer visible:

@Override
protected void onPause() {
    // Unregister since the activity is about to be paused.
    LocalBroadcastManager.getInstance(this).unregisterReceiver(aLBReceiver);
    super.onPause();
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents