2

I'm trying to understand a particular bit of logic in IntentService, specifically, in ServiceHandler:

private final class ServiceHandler extends Handler {
    public ServiceHandler(Looper looper) {
        super(looper);
    }

    @Override
    public void handleMessage(Message msg) {
        onHandleIntent((Intent)msg.obj);
        stopSelf(msg.arg1);
    }
}

From what I can tell, stopSelf() is being called multiple times - once for every startService call. If there are multiple items to handle, will stopSelf not interrupt the flow of the pending items? Clearly that's not what's happening, since IntentService actually works, but why? Seems like stopSelf should be called after all the Intents are handled.

Another question - when will the HandlerThread created in onCreate actually stop? Clearly it's not halted by stopSelf?

Melllvar
  • 2,056
  • 4
  • 24
  • 47
  • You don't need to call `stopSelf` for an `IntentService`. More info here: http://stackoverflow.com/questions/10250745/proper-way-to-stop-intentservice – Gennadii Saprykin Apr 22 '16 at 22:47
  • Indeed, because `IntentService` does the actual calling. My question is about the internal workings of the class. – Melllvar Apr 22 '16 at 22:48

2 Answers2

2

The stopSelf(int startId) method will only stop the Service if the most recent time it was started was with startId. If the IntentService is started again while it's still handling an Intent, a different startId is delivered to it, so calling stopSelf() with a previous startId will not stop it.

The HandlerThread started in onCreate() will die when the Service instance does, as its Looper is terminated in the IntentService's onDestroy() method.

Mike M.
  • 38,532
  • 8
  • 99
  • 95
1

stopSelf(int) calls stopSelfResult(int) which says:

Stop the service if the most recent time it was started was startId. This is the same as calling stopService(Intent) for this particular service but allows you to safely avoid stopping if there is a start request from a client that you haven't yet seen in onStart(Intent, int).

Since IntentService only does work in order, it won't actually stop until the last startId is sent to stopSelf

ianhanniballake
  • 191,609
  • 30
  • 470
  • 443