Prevent Android Service From Being Killed By OS

ぃ、小莉子 提交于 2019-12-12 02:36:00

问题


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.

Cheers


回答1:


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

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

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.




回答2:


The best way to stop a service being killed by android is to create a persistant notification. This will make android keep the service alive at all costs because it displays something visible.



来源:https://stackoverflow.com/questions/21512809/prevent-android-service-from-being-killed-by-os

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