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();
}
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.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With