getLooper()在启动HandlerThread

时间:2015-10-08 15:55:43

标签: android android-handler android-looper android-handlerthread

我有一个类HandlerThread,它看起来像这样:

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!”);
  }

}

如上所述,prepare()函数启动线程&等待run()完成,然后尝试获得looper。

在另一个课程中,我创建了一个MyHandlerThread&的实例。开始吧:

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

在控制台中显示的日志:

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

为什么在prepare()函数中,调用getLooper()会返回 null 虽然线程已经启动(run()已执行)?

1 个答案:

答案 0 :(得分:4)

HandlerThread Looper已在HandlerThread#run()中初始化。

如果重写方法而不调用super.run(),则不会执行超类的初始化代码。