How to use LocalBroadcastManager in Android?
Mar 25, 2020
Advantages of using LocalBroadcast Receiver over Broadcast Reciever?
- Secure Out: Your broadcasted data remains inside the App. So other apps can not receive your data
- Secure In: Your app will not receive Data from other apps Broadcast.
- 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.