Android keep BroadcastReceiver while the app is closed

荒凉一梦 提交于 2019-12-25 00:38:02

问题


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.



来源:https://stackoverflow.com/questions/22283851/android-keep-broadcastreceiver-while-the-app-is-closed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!