Android: Why can't I create a handler in new thread Android: Why can't I create a handler in new thread multithreading multithreading

Android: Why can't I create a handler in new thread


You could also use a HandlerThread like this:

HandlerThread thread = new HandlerThread("MyHandlerThread");thread.start();Handler handler = new Handler(thread.getLooper());

HandlerThreads have a Looper associated with them, so this wouldn't throw an exception.


The Thread's lifecycle is finished right after run method returns. But since you are creating a Handler in this thread, the Handler needs the thread to be running for it to receive messages and process them.

So for this to happen, run method should not exit. Hence you need a Looper to wait indefinitely and process messages that arrive to Handler.

new Thread(new Runnable() {        public void run() {            Looper.prepare();            Handler handler = new Handler();            Looper.loop();        }    }).start();


Short Answer: Because the thread you're trying to attach the Handler on, doesn't have a looper. And so the constructor of Handler class is throwing exception. You could have used a HandlerThread class instead, This is just a handy class provided by the Android framework.

Please read below for whats happening under the hood.

Lets first try to discuss all parts individually.

  1. Thread:

a. A thread is just a execution flow. A thread by default is suppose to just execute its runnable(if provided) or call its run method. Upon calling new Thread.start(). A thread just dies and Gc'd when the run method executes all the statement written inside the run(){ ---- }.

b. There is a concept of Looper in Android. Which basically makes the thread a blocking thread. Putting simply it just doesn't let the thread die. It goes in a blocking state and waiting for more messages to again resume its execution.

Below is how you'd setup a blocking thread i.e a thread with a looper.

  new Thread(new Runnable() {    public void run() {        Looper.prepare();        Looper.loop();    }}).start();

Here a thread is created which doesn't just die after executing the Looper.loop() statement. Instead it loops and goes in a blocking state. Now you must be asking what is the meaning of blocking state, how the thread will come out of the blocking state ? how do i finally release this thread now ? This is where Handler comes in

  1. Handler:

a. It always attaches itself to the Looper of the thread, on which its instance is created.

b. It then processes those messages of the thread it attaches to.

Putting together thread and handlers.

new Thread(new Runnable() {        public void run() {            Looper.prepare();            handler = new Handler();            Looper.loop();        }    }).start();

a. How the handler gets attached to this newly created thread. b. The thread is setup as a blocking looper thread. So this is not going to die.

now, we can 1. Send message on this handler.2. Post runnable on this handler.

Both of them will be executed on the attached thread.

You have an option to either extend the Handler class and implement method handleMessage(Message msg). or you just provide implementation of the Handler.Callback in the constructor of the handler class. In either way the handleMessage(Messages msg) will be called on the attached thread.

To quit the thread you can send a specific type of message type, and upon receiving that message you'd just call Looper.myLooper().quit()

class LooperThread extends Thread {   public Handler mHandler;   public void run() {      Looper.prepare();      mHandler = new Handler() {          public void handleMessage(Message msg) {              // process incoming messages here              if(msg.what == -1){              Looper.myLooper().quit();              }          }      };      Looper.loop();   }}

I hope it helped understanding the overall concept.