33

I've read a lot around Android service. As I understand, the lifecycle is:

void onCreate() 
    void onStart(Intent intent) 
    ...
void onDestroy()

http://www.linuxtopia.org/online_books/android/devguide/guide/topics/fundamentals.html

But there's is no onStop method. Questions:

  • Why isn't there a stop method?
  • What happens when a stopService request is made on my Service? (from outside, perhaps by Android itself). Can I detect this event?
  • I'd like to enforce (or at least verify) that my service is a singleton within a process. How can I do this (or does Android enforce this behind the scenes)?

For context, I have some resources I'd like to allocate and release while the service is running (in a "started"), and another set of resources I'd like to allocate and release while the service is a "created" state.

user48956
  • 14,850
  • 19
  • 93
  • 154

1 Answers1

60

As I understand, the lifecycle is:

onStart() has been deprecated for a few years. onStartCommand() is the current lifecycle method.

Why isn't there a stop method?

Because there is no need for one.

What happens when a stopService request is made on my Service?

You will be called with onDestroy().

Can I detect this event?

You can override onDestroy().

I'd like to enforce (or at least verify) that my service is a singleton within a process. How can I do this (or does Android enforce this behind the scenes)?

Services are natural singletons. There will be 0 or 1 instance of your service at any given time.

For context, I have some resources I'd like to allocate and release while the service is running (in a "started"), and another set of resources I'd like to allocate and release while the service is a "created" state.

The "created" state is used both with the command pattern (startService() and onStartCommand()) and the binding pattern (bindService() and onBind()). Hence, if you call startService(), your service will be purely in the "created" state for hopefully less than a millisecond.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 6
    Keep in mind that if you call bindService with BIND_AUTO_CREATE, onDestroy() won't get called until you unbind – aaronvargas May 30 '14 at 16:56
  • 1
    I observed that `onDestroy()` is not called when device shuts down. Is there any other callback that can be overriden in that case ? – sdabet Jul 29 '16 at 08:27
  • 1
    @fiddler: There is no guarantee that `onDestroy()` will be called, in a few cases (Force Stop, your app crashes, emergency need for system RAM), not just on power down. There is no callback for when Android just terminates your process. *Specifically* with respect to power down, you could try registering a `BroadcastReceiver` for [`ACTION_SHUTDOWN`](https://developer.android.com/reference/android/content/Intent.html#ACTION_SHUTDOWN), but I would not count on having time to do anything significant. – CommonsWare Jul 29 '16 at 10:51