简体   繁体   English

当Android系统杀死我的应用程序时,如何保持后台服务处于活动状态?

[英]how to keep my background service active when android system kills my app?

I have a background service which runs in background to track screen on and off events. 我有一个后台服务,该服务在后台运行以跟踪屏幕打开和关闭事件。 its started as below : 其开始如下:

Intent intentService = new Intent(context, UnlockdService.class);
context.startService(intentService);

And it is returning Service.START_REDELIVER_INTENT in the method onStartCommand. 它在onStartCommand方法中返回Service.START_REDELIVER_INTENT But still when android system kills app this thread dies as well. 但是,当android系统杀死应用程序时,该线程也会死亡。

How can I prevent it? 我该如何预防?

I think it's a better solution to have a BroadcastReceiver instead of a Service. 我认为使用BroadcastReceiver而不是Service是更好的解决方案。 In your onReceive, you could then start your service to do its work, and then the service could self terminate - maybe you could use an IntentService if your work is one shot. 然后,在onReceive中,您可以启动服务以完成其工作,然后该服务可以自行终止-如果您的工作是一次性的,则可以使用IntentService。

If you still want a Service, you can make it less likely to be killed by having a permanent notification in the notification bar, but that can be bad from a user perspective. 如果仍然需要服务,则可以通过在通知栏中显示永久通知来减少被杀死的可能性,但是从用户的角度来看这可能很糟糕。 I strongly recommend going the broadcast receiver route. 我强烈建议您使用广播接收器路线。

解决方案非常简单:从onStartCommand()返回START_STICKY onStartCommand()完成工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我清除所有最近的应用程序时,Android系统会在Android v7.1.2上终止我的应用程序服务 - When I clear all recent apps, android system kills my app service on Android v7.1.2 如何在系统杀死Android之前运行的活动中重新启动我的应用程序? - How to restart my app in the activity that was running before system kills it android? 控制android如何杀死我的应用 - Control how android kills my app Android O进入后台后立即终止我的服务 - Android O kills my Service as soon as it goes to the background 在后台运行一段时间后,Android杀死了我的应用 - Android kills my app after some time in background Android杀死了我的phonegap应用 - android kills my phonegap app 系统在onStop()状态处于闲置状态后杀死了我的android应用。 如何避免或发现这种情况? - System kills my android app after some idle in onStop() state. How to avoid or detect this situation? 我的华为杀死了我的wakelock安卓应用 - My Huawei kills my wakelock android app 保持我的会话处于活动状态的android应用 - Keep my session active android app 如何让电台应用程序在我的 Android 应用程序的后台继续播放 - How to make a radio app keep playing in the background of my Android App
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM