Lifetime of BroadcastReceiver with regard to Andro

2019-01-26 09:07发布

问题:

If I declare a BroadcastReceiver via the mainfest file for a system broadcast (let's say for example ACTION_POWER_DISCONNECTED) the the system will call it every time the specific broadcast is send so the lifetime of the BroadcastReceiver is unrestricted.

But there are also broadcasts which can not be registered via the manifest file. For these broadcasts we have to call context.registerReceiver with a corresponding IntentFilter. Let's say I create a BroadcastReceiver for BOOT_COMPLETED and call context.registerReceiver from it and never call unregisterReceiver does this receiver also lives forever (until the phone is rebooted)?

Apps that target Android O can no longer register broadcast receivers for implicit broadcasts in their manifest. An implicit broadcast is a broadcast that does not target that app specifically.

If my conjecture from above is right this would be an easy workaround for the system change (of course you shouldn't do it this way but it would be possible). So does a BroadcastReceiver which is registered after a BOOT_COMPLETED broadcast have the same lifetime (stays until the next reboot) as a BroadcastReceiver which is automatically registered via the manifest?

回答1:

Let's say I create a BroadcastReceiver for BOOT_COMPLETED and call context.registerReceiver from it and never call unregisterReceiver does this receiver also lives forever (until the phone is rebooted)?

First, BOOT_COMPLETED is one of those actions, that still will behave like they were before, meaning restriction introduced in "O" do not concern to that action.

As soon as the process of your app is killed by the system or as soon as system clears your app's memory (as a result of low-memory of device), your broadcast registration will be lost. Otherwise I cannot see how this limitation will result in a better battery experience.

So does a BroadcastReceiver which is registered after a BOOT_COMPLETED broadcast have the same lifetime (stays until the next reboot) as a BroadcastReceiver which is automatically registered via the manifest?

If above mentioned cases are not met, i.e. the process of your app stays alive and app is not cleared from memory because of memory shortage - then yes. Once entered into cached state (the state with no active Android component) the registration will be lost again.

This short video by Nasir Khan will be helpful.