- public class HandlerThread extends Thread {
- int mPriority;
- int mTid = -1;
- Looper mLooper;
- private @Nullable Handler mHandler;
- public HandlerThread(String name) {
- super(name);
- mPriority = Process.THREAD_PRIORITY_DEFAULT;
- }
- /**
- * Constructs a HandlerThread.
- * @param name
- * @param priority The priority to run the thread at. The value supplied must be from
- * {@link Android.os.Process} and not from java.lang.Thread.
- */
- public HandlerThread(String name, int priority) {
- super(name);
- mPriority = priority;
- }
- /**
- * Call back method that can be explicitly overridden if needed to execute some
- * setup before Looper loops.
- */
- protected void onLooperPrepared() {
- }
- @Override
- public void run() {
- mTid = Process.myTid();
- Looper.prepare();
- synchronized (this) {
- mLooper = Looper.myLooper();
- notifyAll();
- }
- Process.setThreadPriority(mPriority);
- onLooperPrepared();
- Looper.loop();
- mTid = -1;
- }
- /**
- * 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;
- }
- /**
- * @return a shared {@link Handler} associated with this thread
- * @hide
- */
- @NonNull
- public Handler getThreadHandler() {
- if (mHandler == null) {
- mHandler = new Handler(getLooper());
- }
- return mHandler;
- }
关键的就是这些, 很明显的可以看出, handlerThread 在一个子线程里面封装好了 looper 和 handler, 所以这就是为什么在子线程里面使用 handlerThread 直接 run 就可以了.
在 getLooper 里面, handlerThread 对线程是否存在加了一个判断, 因为 handler 在主线程, 而 handlerThread 创建的 Looper 在子线程, 如果子线程没有创建或者子线程的 Looper 没有创建, 那 handler 也不知道给谁发消息. 所以这里 handlerThread 加了一层判断, 确保子线程的 Looper 创建.
关于 handlerThread 的使用场景, 一般就是在子线程中使用, 因为如果按照正常的 handler 使用的话, 需要自己额外在子线程新建一个 Looper(由于主线程已经默认有一个 Looper 了, 所以在主线程可以直接用 handler). 例如在子线程不断地获取数据更新 UI 的时候, 就可以用到 handlerThread.
来源: http://www.jianshu.com/p/5ce05c8edcdd