Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why no Service.onStop method?

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.

like image 307
user48956 Avatar asked Apr 19 '12 21:04

user48956


People also ask

What is used of onStop () method?

onStop() method is called after onPause() method when activity goes in background. This method can be used to stop Api calls etc.

What is the use of an onStop () function in Android?

The onStop() function is called when the application enters the stopped state. In this state, the activity is no longer visible to the user.

What is the difference between onPause and onStop?

If screen times out on your activity, then onPause is called. After sometime if you will not open the screen then onStop will be called.

Is onPause always called before onStop?

onPause() is always called. This is guaranteed. If you need to save any state in your activity you need to save it in onPause() . onStop() may be called after onPause() , or it may not.


1 Answers

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.

like image 64
CommonsWare Avatar answered Oct 15 '22 03:10

CommonsWare