Home » Android » android – LocalBroadcastManager vs Context.registerReceiver(), Context.sendBroadcast(Intent), and Context.unregisterReceiver() are they same?

android – LocalBroadcastManager vs Context.registerReceiver(), Context.sendBroadcast(Intent), and Context.unregisterReceiver() are they same?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I was using Context.registerReceiver(), Context.sendBroadcast(Intent) , and Context.unregisterReceiver()

but when I saw the class LocalBroadcastManager, it has registerReceiver(), sendBroadcast(Intent) ,andunregisterReceiver() like in Context.

I’m confused. When should I use the LocalBroadcastManager? are they same in Context?

Regards,

Thanks…

How to&Answers:

LocalBroadcastManager is as its name says, an implementation of the broadcast methods that are only available to your app. This has some benefits, with the biggest being safety, one less hole to watch out for. In terms of implementation, there are a few things to keep in mind:

  • This class is from the Android Support Library
  • The method calls have to be prefaced with LocalBroadcastManager.getInstance([CONTEXT]) where [CONTEXT] is a subclass of the Context class, such as Activity.
  • When you use this class, it is purely for your app. Using it to register receivers and make broadcasts that are system wide will fail.

So this class is not the same as Context, it is simply a very specific, app-only implementation of Context’s receiver/broadcast methods. You should use it when there is absolutely no point for your listener to listen on global (system-wide) broadcasts and when your broadcast does not need to target anything outside your app.