/** * 返回handlerThread所关联的Looper,如果handlerThread线程已经死亡则返回null * 如果handlerThread线程未执行过start()方法的话就会阻塞调用线程 * * @return The looper. */ public Looper getLooper() { // 如果handlerThread线程未启动或已经死亡,则返回null if (!isAlive()) { return null; }
boolean wasInterrupted = false;
// If the thread has been started, wait until the looper has been created. // 获取Looper时首先要确保线程已经启动并且mLooper已经赋值成功,否则将会返回null导致传递给Handler时会抛出java.lang.NullPointerException: // Attempt to read from field 'android.os.MessageQueue android.os.Looper.mQueue' on a null object reference异常 synchronized (this) { while (isAlive() && mLooper == null) { try { // 调用线程与handlerThread并不处于同一个线程,所以并不能保证当执行handlerThread.getLooper时handlerThread线程中mLooper已经赋值完毕。 // 所以如果mLooper还未赋值成功时就执行wait()阻塞调用线程并释放锁对象,直到handlerThread线程获取到执行权并且对mLooper赋值完成之后handlerThread线程 // 会通过notifyAll()来通知正在wait()的调用线程,此时调用线程就可以得到正确的mLooper对象而不是空 wait(); } catch (InterruptedException e) { wasInterrupted = true; } } }
/* * 如果线程还未来得及被notify就收到了中断请求则直接中断调用线程 */ if (wasInterrupted) { Thread.currentThread().interrupt(); }
return mLooper; }
@NonNull public Handler getThreadHandler() { if (mHandler == null) { mHandler = new Handler(getLooper()); } return mHandler; }
/** * 退出Looper消息循环 * 如果队列中还有延时任务未执行则将延时任务全部清除,也就是说延时任务直接被抛弃得不到执行 * 如果队列中还有非延时任务未执行则会一直等到所有非延时任务都得到执行之后才真正停止Looper消息循环 * * @return True if the looper looper has been asked to quit or false if the * thread had not yet started running. */ public boolean quitSafely() { Looper looper = getLooper(); if (looper != null) { looper.quitSafely(); return true; } return false; }
/** * 返回线程id */ public int getThreadId() { return mTid; } }