Search code examples
androidbroadcastreceiverlocalbroadcastmanager

Why does LocalBroadcastManager.getInstance(Context context) require context as a parameter?


If I am able to register a receiver like so:

LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("myStringFilter"));

and send out a broadcast like so:

Intent intent = new Intent("myStringFilter");
LocalBroadcastManager.getInstance(new Activity()).sendBroadcast(intent);

why even require Context for getInstance? If I can just say new Activity() and it still works, what is the point?


Solution

  • Right now, LocalBroadcastManager uses the supplied Context for is to call getApplicationContext() on it. While new Activity() may work at present wherever you tested it, I would not rely upon that behavior necessarily working on all past/present/future versions of Android.

    LocalBroadcastManager needs a Context in order to work with a Handler and Looper for the main application thread, and it uses Application for that (rather than some other Context) to prevent memory leaks.

    You are welcome to examine the source code to LocalBroadcastManager to learn more about its inner workings.