Android: When should I use a Handler() and when should I use a Thread?

Handler and Thread are two different things, but they do not contradict each other. You can have a Handler and a Thread at the same time and actually each Handler must be running in a Thread.

For more details, you may want to check out this article.

enter image description here


If whatever you are doing is "heavy" you should be doing it in a Thread. If you do not explicitly start it in its own thread, then it will run on the main (UI) thread which may be noticeable as jittery or slow to respond interface by your users.

Interestingly when you are using a thread it is often useful to also use a Handler as a means of communication between the work thread that you are starting and the main thread.

A typical Thread/Handler interaction might look something like this:

Handler h = new Handler(){
    @Override
    public void handleMessage(Message msg){
        if(msg.what == 0){
            updateUI();
        }else{
            showErrorDialog();
        }
    }
};

Thread t = new Thread() {
    @Override
    public void run(){
        doSomeWork();
        if(succeed){
            //we can't update the UI from here so we'll signal our handler and it will do it for us.
            h.sendEmptyMessage(0);
        }else{
            h.sendEmptyMessage(1);
        }
    }   
};

In general though, the take home is that you should use a Thread any time you are doing some work that could be long running or very intensive (i.e. anything network, file IO, heavy arithmatic, etc).


Handler and Thread are really 2 different things.

A thread must be created to execute long running jobs.

A Handler is very convenient object to communicate between 2 threads (for instance : a background thread need to update the UI. You can use a Handler to post some Runnable from your background thread to the UI thread).

So you don't have the choice between Handler or Thread. Use a thread to do heavy jobs! (you can use a Handler if your background thread will trigger some job to be done in another thread - most of the time the UI thread)