I would like to ask someone to explain me please, what are the main differences between HandlerThread and IntentService, and what are the main use-case scenarios?
I understand that HandlerThread contains a Looper, which managing the messageQueue, which is feed by the Handler. As far as I understand, you can push task for the HandlerThread and it's going to execute. It's great thing to use for nonUI related, long running operations, where you can push the results back onto the UI by runOnUiThread().
In contrast, IntentService is good for long running, nonUI related operations, can execute tasks in sequence, when it's done with the jobs it's calling selfStop() to shut itself done. If an IntentService is working on a task, when a new request arriving it's adding to the queue and processing the 2nd, when it's completed with the 1st.
From my point of view they are doing the same job, in a very same way. Let assume I have an app, where the user TAP on a button, I'm starting to download a file. If the user taps multiple times, a new task is getting queued, launching the 2nd only when the 1st is done. What should I use? IntentService or HandlerThread?
So, after checking the source code of both the HandlerThread and the IntentService I found the following:
IntentService onCreate() method, creating the working thread:
@Override
public void onCreate() {
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
IntentService own handler, needed to kill the service after the work is done:
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);
}
}
In my reading IntentService is the combination of HandlerThread and Service.
Any further answers and solutions are more than welcome !