防止Android服务被操作系统杀死 [英] Prevent Android Service From Being Killed By OS

查看:731
本文介绍了防止Android服务被操作系统杀死的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个服务,该服务在onStartCommand处返回START_STICKY.但是,一段时间后,我注意到我的应用已被操作系统杀死.

I have created a service that is returning START_STICKY at the onStartCommand. However, after sometime, I notice that my app has been killed by the OS.

是否可以使用任何方法/一段代码来防止该应用被操作系统杀死?我知道这可能不属于最佳做法. 还是我们可以使用其他方法,例如反复检查应用程序是否正在运行,如果没有运行,则要启动该应用程序?

Is there any method/piece of code that I can use to prevent the app from being killed by the OS? I know this may not fall under the best practices. Or is there some other method that we can use like repeatedly check if the app is running, and to start the app if it is not?

非常感谢您对此的见识.

Your insight on this is very much appreciated.

欢呼

推荐答案

您无法防止进程被杀死.如果操作系统决定终止您的进程,您将被杀死.时期.

You cannot prevent your process from being killed. If OS decide to kill your processes you will be killed. Period.

START_STICKY不会对其他答案有任何误解-有关该值的文档说:

The START_STICKY will not do any magic os other answer incorrectly tells - docs about that value say:

如果此服务的进程在启动时被杀死(之后 从onStartCommand(Intent,int,int))返回,然后将其保留在 起始状态,但不要保留此交付意图.后来的系统 将尝试重新创建服务.因为它处于启动状态, 它将保证在之后调用onStartCommand(Intent,int,int) 创建新的服务实例;如果没有任何挂起的开始 传递给服务的命令,它将以null调用 意向对象,因此您必须小心检查这一点.

If this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand(Intent, int, int) after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.

这篇关于防止Android服务被操作系统杀死的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆