16

From my little android knowledge I understand that android OS can kill my service under extreme memory conditions.

I have created a service that returns START_STICKY. The service is meant to run in background.

If android is about to kill my service, will it call onDestroy ?

And when it restarts it would it call onCreate ?

bitoiu
  • 6,893
  • 5
  • 38
  • 60
Ahmed
  • 14,503
  • 22
  • 92
  • 150

2 Answers2

14

See here, the dev guide. http://developer.android.com/reference/android/app/Service.html#ProcessLifecycle

onCreate() is only called when the process starts, which can either be the first time the service is running, or if it was killed on restarted, essentially this is called whenever it starts.

onStartCommand() is called whenever a client calls startService().

When a service is destroyed / completely stopped, Android is supposed to call onDestroy() on that service. I think it's possible for that to not happen (e.g. process is killed not through Android system). In the case of a bound service, this is when there are not more active client binders.

Edit: onCreate() Service starts; onStartCommand()someone uses service; onDestroy()Service is killed / stopped.

David Adrian
  • 1,079
  • 2
  • 9
  • 24
  • 1
    Just like to remind that when a started `Service` is killed and restarted by system, it **WON'T** call `onStartCommand()` , only `onCreate()`. I had a receiver registered in the former and unregister in `onDestroy()`, and in some situation when service is killed - restarted - killed in background, it threw a Fatal Exception "Receiver not registered" when `onDestroy`. In Short: initialize your receiver / data **in `onCreate()`, not in `onStartCommand()`**. – Samuel T. Chou Aug 21 '20 at 08:14
4

If someone calls Context.startService() then the system will retrieve the service (creating it and calling its onCreate() method if needed) and then call its onStartCommand(Intent, int, int) method with the arguments supplied by the client

...

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the service's onDestroy() method is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy().

http://developer.android.com/reference/android/app/Service.html

EDIT: Quick answer. Yes to both questions

user1378730
  • 930
  • 9
  • 18