Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling stopSelf() in Service while thread is running

Suppose I have code in the onStart() handler of my Service to launch a thread to do some stuff and then call stopSelf().

stopSelf() gets called before the thread finishes. What exactly happens?

I've tested this out myself and my thread continues to execute until it is finished. Does Android hear the stopSelf() call, but postpone it until the thread is finished?

 @Override
 public void onStart(Intent intent, int startid) {
  new Thread(new Runnable() {
      public void run() {
        // TODO some long running operation
      }
    }).start();
  stopSelf();
 }
like image 800
Andrew Avatar asked Sep 14 '10 15:09

Andrew


People also ask

When should you call stopSelf?

You should call stopSelf () to stop a service. After you call it, the Android Framework will call onDestroy() method automatically. Actually, these onXXX() methods(the prefix "on" implies that these methods are callbacks for the system) should be called by the system, not the developers.

What is stopSelf service?

stopSelf() is used to always stop the current service. stopSelf(int startId) is also used to stop the current service, but only if startId was the ID specified the last time the service was started. stopService(Intent service) is used to stop services, but from outside the service to be stopped.


1 Answers

stopSelf() gets called before the thread finishes. What exactly happens?

The thread runs to completion.

Does Android hear the stopSelf() call, but postpone it until the thread is finished?

No. Your Service is still destroyed at the point of the stopSelf() call. You're just leaking a thread and the Service object, at least until the thread terminates.

You may wish to consider switching to IntentService, as it integrates the background-thread-and-stopSelf() pattern.

like image 157
CommonsWare Avatar answered Oct 03 '22 23:10

CommonsWare