How to use LocalBroadcastManager in Android?

Rohit Singh
Mar 25, 2020

--

Advantages of using LocalBroadcast Receiver over Broadcast Reciever?

  1. Secure Out: Your broadcasted data remains inside the App. So other apps can not receive your data
  2. Secure In: Your app will not receive Data from other apps Broadcast.
  3. Drains less battery: It is a more efficient way to send/receive data locally.

How to change your global Broadcast to LocalBroadcast?

LocalBroadcastReceiver is the same as BroadcastReceiver in Android. So if you know how to use BroadcastReceiver then you have got this. The code is almost similar.

1) Create Instance

LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);

2) For registering BroadcastReceiver

Replace

registerReceiver(new YourReceiver(),new IntentFilter("YourAction"));

With

localBroadcastManager.registerReceiver(new YourReceiver(),new IntentFilter("YourAction"));

3) For sending a broadcast message

Replace

sendBroadcast(intent);

With

localBroadcastManager.sendBroadcast(intent);

4) For unregistering BroadcastReceiver

Replace

unregisterReceiver(mybroadcast);

With

localBroadcastManager.unregisterReceiver(mybroadcast);

And that's it.

Putting up content takes a lot of time and effort πŸ˜“.
πŸ‘ clap πŸ‘ If you think you learned something from this article.
You can find me on Stackoverflow,Github,and,on Linkedin.
Give feedback and feel free to correct mistakes.

--

--

Rohit Singh
Rohit Singh

Written by Rohit Singh

Android Developer | Arizona State University | NASA Psyche Research Aide

Responses (1)