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();
}
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.
精彩评论