Calling stopSelf() in Service while thread is running Calling stopSelf() in Service while thread is running multithreading multithreading

Calling stopSelf() in Service while thread is running


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.


If you call stopself() from inside the thread. You can call stopSelf() at any point in you thread whenever you want the service to stop. But even then the thread will continue running. If you want service to stop as soon as thread completes then call stopSelf() on last line of your thread.