Search code examples
androidandroid-handlerandroid-looperandroid-handlerthread

getLooper() returns null after started HandlerThread


I have an class extends HandlerThread, it looks like this:

public class MyHandlerThread extends HandlerThread {

  private Object lock;

  //constructor
  public MyHandlerThread() {
     super(“MyHandlerThread”);
     lock = new Object();
  }

  public void prepare() {
     //starts the handler thread
     start();

     //Wait for thread starting
     Log.d(TAG, "wait for thread starting…");
     synchronized (lock) {
        try {
            lock.wait(5000);
        } catch (InterruptedException e) {
            Log.e(TAG, "Failed to wait for thread to start");
        }
     }

     //WHY getLooper() returns null here?
     if(getLooper() == null) {
         Log.d("GET LOOPER NULL!");
     }
  }

  @Override
  public void run() {
    Log.d("run() begin...");
    initializeSomeObjects()
    Log.d(“initialise objects done!”);

    //Notify that run() finished
    synchronized (lock) {
       lock.notify();
    }
    Log.d("run() end!”);
  }

}

As you see above, the prepare() function starts the thread & wait for run() to be finished, then try to get looper.

In another class, I create an instance of MyHandlerThread & start it:

MyHandlerThread myThread = new MyHandlerThread();
myThread.prepare();

Logs showing in console:

wait for thread starting…
run() begin...
initialise objects done!
run() end!
GET LOOPER NULL!

Why in prepare() function, call to getLooper() returns null though the thread is already started (run() is executed)?


Solution

  • HandlerThread Looper is initialized in HandlerThread#run().

    If you override the method and don't call super.run(), the init code from superclass is not executed.