Howdy Friends!
In Simple language Broadcast Receivers respond to broadcast messages from other applications or from the system itself. These messages are sometime called events or intents.
e.g an event is fire and if your application has a broadcast reciever then you can listen to the event and perform certain action like SMS Recievers (that responds when a SMS is delivered to the android system).
In this Blog we are going to create a local reciever that will respond to the local event created by our application.
LocalBroadcastManager
This is a helper class to register for and send broadcasts of Intents to local objects within your process.
This helper class generate local events thus it will give you a much more efficient implementation (no cross-process communication needed) and allow you to avoid thinking about any security issues related to other applications being able to receive or send your broadcasts.
You can either dynamically register an instance of this class with Context.registerReceiver()
or statically publish an implementation through the <receiver>
tag in your AndroidManifest.xml
.
Note: If registering a receiver in your Activity.onResume()
implementation, you should unregister it in Activity.onPause()
. (You won’t receive intents when paused, and this will cut down on unnecessary system overhead). Do not unregister in Activity.onSaveInstanceState()
, because this won’t be called if the user moves back in the history stack.
Let us now generate some events and receive in our Activity(s) receiver.
Step 1. Create a local event
1 2 3 4 5 6 |
private void sendMessage() { Intent intent = new Intent("my-event"); // add data intent.putExtra("message", "from local broad cast reviever"); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } |
Step 2. Create a Broadcast Receiver in the class where we want to perform an action
1 2 3 4 5 6 7 8 9 |
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Extract data included in the Intent Toast.makeText(getApplicationContext(), intent.getStringExtra("message"), Toast.LENGTH_SHORT).show(); //do other stuff here lke: // setNotificationIconBadge(); } }; |
Step 3. Register and Unregister the broadcast receiver
1 2 3 4 5 6 7 8 9 10 11 12 13 |
//register your activity onResume() @Override public void onResume() { super.onResume(); LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("my-event")); } //Must unregister onPause() @Override protected void onPause() { super.onPause(); LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver); } |
Enjoy listening to the local events.
That’s all folk.. Stay Updated