Android keep BroadcastReceiver while the app is cl

2019-09-02 13:58发布

问题:

I use BroadcastReceiver of ACTION_BATTERY_CHANGED to get an event every time the battery is 50%. I can't declare ACTION_BATTERY_CHANGED in manifest, so I declared the BroadcastReceiver in a Service (START_STICKY).

But, when I remove the app from recent apps screen the BroadcastReceiver stops getting battery change events. How can I keep it in background?

*In many apps that show battery percent in status bar, the percent is updated while the app is closed. How?

回答1:

You really cannot do what you are trying to do. There is no way to keep your application running forever, and you can only catch ACTION_BATTERY_* where your app is running.

Since the broadcast is sticky, though, you can do something else. Set an alarm (AlarmManager) so that you wake your app up, periodically. When you register a receiver, in your code, Android will deliver any intents that were broadcast while your app was not running.