0

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

Ela Buwa
  • 1,652
  • 3
  • 22
  • 43
  • "I know this may not fall under the best practices" -- an everlasting service is an anti-pattern on Android, unless the user perceives that you will deliver continuous value. Usually, there is a better solution, such as doing work periodically using `AlarmManager`. – CommonsWare Feb 02 '14 at 16:22
  • maybe this will help you [How can we prevent service from killing by OS in android][1] [1]: http://stackoverflow.com/questions/9696861/how-can-we-prevent-service-from-killing-by-os-in-android – xiaoyee Mar 16 '15 at 03:22

2 Answers2

1

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.

japk
  • 619
  • 6
  • 10
  • 2
    This reduces the odds that your process will be terminated. It will not prevent it. The user can still Force Stop the app from settings, for example. – CommonsWare Feb 02 '14 at 16:21
  • @CommonsWare very true, the system may also kill it if memory is extremely low, but because it's visible to the user, it has high priority to be kept alive by the system – japk Feb 02 '14 at 17:21
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.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141