int mPriority; int mTid = -1; Looper mLooper; private @Nullable Handler mHandler;
public HandlerThread(String name) { super(name); mPriority = Process.THREAD_PRIORITY_DEFAULT; }
函数
run 函数很简单,先 Looper.prepare(),给当前线程的初始化一个 Looper 对象,需要注意的是,这个方法不能在当前线程多次调用,会抛出 new RuntimeException("Only one Looper may be created per thread"); 异常,不明白的可以去看这一篇Handler 源码大白话。有一个 onLooperPrepared() 方法你可以去重写,主要是 Looper.loop() 调用前的一些准备操作
/** * Call back method that can be explicitly overridden if needed to execute some * setup before Looper loops. */ protected void onLooperPrepared() { }
/** * This method returns the Looper associated with this thread. If this thread not been started * or for any reason isAlive() returns false, this method will return null. If this thread * has been started, this method will block until the looper has been initialized. * @return The looper. */ public Looper getLooper() { if (!isAlive()) { return null; } // If the thread has been started, wait until the looper has been created. synchronized (this) { while (isAlive() && mLooper == null) { try { wait(); } catch (InterruptedException e) { } } } return mLooper; }
关闭Looper,或者使用quitSafely() 这是一个安全的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
public boolean quit() { Looper looper = getLooper(); if (looper != null) { looper.quit(); return true; } return false; }
public boolean quitSafely() { Looper looper = getLooper(); if (looper != null) { looper.quitSafely(); return true; } return false; }