Background

On Android, there are 2 possible ways to listen to system events via BroadcastReceivers :

  • statically, via the manifest
  • programmatically, via the code.

Since some projects contain a lot of activities, services, and "manager"-classes , it could be useful to have a single BroadcastReceiver that will notify all of its listeners on the app about what has happened, instead of having multiple BroadcastReceivers being used (and their code handling).

An example of such a BroadcastReceiver, is the one that listens to the connectivity changes:

@Override
public void onCreate() {
    super.onCreate();
            ...
    registerReceiver(new ConnectivityChangedBroadcastReceiver(), new IntentFilter(
            ConnectivityManager.CONNECTIVITY_ACTION));
            ...
    }

The question

The purpose is to listen to the events while the app is "alive" (by services and/or activities) .

Using the manifest would miss this purpose, as it will wake the app each time the event occurs, even if the app doesn't need it.

Thing is, unregistering doesn't occur, and maybe it causes the OS treat the app in a different way because of it.

Does having a call to "registerReceiver" on the class that extends from Application is a good known practice?

Does it have any side effects and things to know about when using it?

Is there any alternative to this?

I just want to be sure it's considered safe to use.

有帮助吗?

解决方案

we can't really know what is good or better for you.

I advise you to learn more about the difference between the registration ways of the receiver:

1/ in the manifest : the handler of the receiver will be triggered each time that the correspondent event comes. Example: the messenger of facebook is lunched every time that you have internet connection to show you your notifications... or other applications are lunched when you connect to propose updates ... in other words, the receiver is always registered.

2/ in a service or an activity or an application : the receiver will be unregistered when the context of where it is registered is killed. in other words, it depends totally of the context where it is registred , and you are obliged to unregister it somewhere in the code. exemple : one activity is waiting that a service ( which is doing something in the background) sends an alert to update something , then you can register the receiver in your onResume() and unregester it in your onPause().

Conclusion : It depends only in the life-cycle requirement of the receiver.

see also Broadcast Receiver Register in Manifest vs. Activity

Main difference between Manifest and Programmatic registering of BroadcastReceiver

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top