Example of a LocalBroadcastManager
suggest changeA 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.
- The broadcast stays in the application process.
- 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();
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents