问题描述
我要保持一个服务在后台运行,即使在我的应用程序被杀害。我使用 android.intent.action.USER_ preSENT
事件,但该服务仅在屏幕解锁运行。我试图 android.intent.action.BOOT_COMPLETED
,但它需要下载的应用程序后至少一次重新启动手机。
I want to keep a service running in background, even when my app is killed. I'm using android.intent.action.USER_PRESENT
event but the service only runs when the screen is unlocked. I tried android.intent.action.BOOT_COMPLETED
but it needs to restarts the phone at least once after downloading the app.
理想我想开始我的服务的所有X分钟,使用 ACTION_TIME_TICK
的实例。然后启动该服务之前检查条件(电池电量,网络连接...)。
Ideally I would start my service all X minutes, using ACTION_TIME_TICK
for instance. Then check conditions (battery level, network connections...) before starting the service.
问题是这样的事件不能声明,并从的manifest.xml
而是在活动地听着,这意味着应用程序是'活着'。
The problem is such event can't be declared and listened from manifest.xml
but rather in an Activity, implying the app to be 'alive'.
有没有办法做我想要呢?
Is there a way to do what I want anyway ?
推荐答案
采取,您可以使用,以确保您的服务是活得很好,如果没有,可以根据需要启动/重新启动。
take a look at AlarmManager
, which you can use to ensure your service is alive and well, if not, start/restart as needed.
您可以AlarmManager第一次您的应用程序的安装后,打开注册。从那时起,说,如果用户重新启动,使用监听 android.intent.action.BOOT_COMPLETED另一个(二)引导服务注册
。 AlarmManager
为您服务
You can register for AlarmManager the first time your app is opened after its installation. From then on, say if user reboots, register your service with AlarmManager
using another (2nd) bootstrap service that listens to android.intent.action.BOOT_COMPLETED
.
有可能是其他considerations与设备睡眠和金额/这类工作你在你的后台服务做的,
There may be other considerations with device sleep, and the amount/kind of work you do in your background service, take a look at this lib and notes as well
AlarmManager
可连续确保您的后台服务是健康的。
AlarmManager
can continuously ensure your background service is healthy.
这篇关于Android的 - 在后台运行服务甚至当应用程序被杀害或设备重新启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!