Android BroadcastReceiver and Activity.onPause()

2019-07-24 16:10发布

问题:

The documentation for BroadcastReceiver says:

If registering a receiver in your Activity.onResume() implementation, you should unregister it in Activity.onPause(). (You won't receive intents when paused, and this will cut down on unnecessary system overhead).

I made an example of Activity A1 that has an inner BroadcastReceiver that updates A1 interface when a Service S1 makes a sendBroadcast. S1 spends around 8 seconds to finish.

When running A1 and hitting the home button for making A1 call onPause, "it still receives the intent from sendBroadcast" and updates the interface, am I missing something or the documentation is wrong?
Thanks

回答1:

The document meant to say that if you unregistered in onPause() then you won't receive broadcast intents when paused. If you do not unregistered then you would continue to receive broadcast intents. You unregistered in onDestroy(), but when the home key is pressed only onStop() is called and onDestroy() will not be called. Thus you continue to receive broadcast.