How to use LocalBroadcastManager in Android?

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.

--

--

--

Android Developer | Arizona State University | NASA Psyche Research Aide

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to Upload files with Ferry GraphQL and Flutter

Alternatives to Jira in 2021 for Self-Hosted

What is DevOps?

Recap: 2019 Qiskit Camp Asia

aerial photo of building in front of mountains

KYVE / Pool economy/How data are stored

Terminal scripts — gog mode.

S1000D For Beginners

Architecture of Annette Platform

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rohit Singh

Rohit Singh

Android Developer | Arizona State University | NASA Psyche Research Aide

More from Medium

Android 13 Developer Preview: Everything you need to know

How to play youtube videos in Jetpack Compose

Making Responsive UI in Android: Part-1

How To Secure Your Android App?