views:

71

answers:

1

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();
 }
+1  A: 

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.

CommonsWare
So, if I understand this correctly, an IntentService will execute the code in onHandleIntent in a thread; so I don't need to do any threading with my code. Also, the IntentService will kill itself when the code is finished executing. If another Intent is passed to the IntentService, it will handle that Intent when the executing one is finished. When all are finished, it kills itself. Outside of the IntentService, all I need do is call startService with my Intent. Yes?
Andrew
Is there any way to force an Intent to the front of the queue? Queuing up these actions is fine most of the time, but say I want the IntentService to hit a web service to pull data. I'd want that to jump everything in the queue and happen right away. The UI thread may not be frozen, but the user is still waiting on that data.
Andrew
@Andrew: "Yes?" -- yes. "Is there any way to force an Intent to the front of the queue?" -- not that I am aware of, though you may be able to replace the queue with a `PriorityQueue` somehow. IIRC, `IntentService` isn't a very big class, so you can perhaps clone it to tune the queue implementation to meet your needs.
CommonsWare
Ok. Thank you for your help
Andrew