HandlerThread 解析及应用

本文我们讲解的是 HandlerThread,可能有部分同学不了解或者没用过这个类。原因很简单,在如今大神们的框架面前,许多的原生类已经不为人所用了,然而早期开发者要想在子线程里更新 UI 则需要在 Thread 里创建一个 Handler。

class MyThread : Thread() {
    private lateinit var mHandler: Handler
override fun <span class="hljs-function"><span class="hljs-title">run</span></span>() {
    super.run()
    Looper.prepare()

    mHandler = object : <span class="hljs-function"><span class="hljs-title">Handler</span></span>() {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            <span class="hljs-keyword">if</span>(msg?.what==0){
                //...处理消息
            }
        }
    }

    Looper.loop()
}

}

复制代码

是不是认为很难受?每次要想在子线程里面处理信息必须每次在子线程里创建 Handler?

然而贴心的 Google 工程师为我们提供了一个自带 Handler 的类,名叫 HandlerThread

类注释

要想学习一个类的构成,首先要从它的类注释看起。

**
 * Handy class for starting a new thread that has a looper. The looper can then be 
 * used to create handler classes. Note that start() must still be called.
 */
public class HandlerThread extends Thread {
    ...
}
复制代码
  • 由它的注释可以看出,这是一个带有LooperThread,这个Looper可以被用于创建Handler,请注意,start()这个方法仍然需要被调用。
  • 总结一下,这个类就是自带 Handler 的线程类。

构造方法

    int mPriority;//优先级
    int mTid = -1;
    Looper mLooper;//自带的Looper
    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;
}
复制代码
  • 这里有两个构造方法,一个HandlerThread(String name),一个HandlerThread(String name, int priority),我们可以自己设定线程的名字以及优先级。注意!是 Process 里的优先级而不是 Thread 的。
    //这是可选的优先级
    public static final int THREAD_PRIORITY_DEFAULT = 0;
    public static final int THREAD_PRIORITY_LOWEST = 19;
    public static final int THREAD_PRIORITY_BACKGROUND = 10;
    public static final int THREAD_PRIORITY_FOREGROUND = -2;
    public static final int THREAD_PRIORITY_DISPLAY = -4;
    public static final int THREAD_PRIORITY_URGENT_DISPLAY = -8;
    public static final int THREAD_PRIORITY_VIDEO = -10;
    public static final int THREAD_PRIORITY_AUDIO = -16;
    public static final int THREAD_PRIORITY_URGENT_AUDIO = -19;
    public static final int THREAD_PRIORITY_MORE_FAVORABLE = -1;
    public static final int THREAD_PRIORITY_LESS_FAVORABLE = +1;
复制代码

其他方法

    
    /*
        在Looper.loop()之前调用的方法,如需要配置可重写
    */
    protected void onLooperPrepared() {
    }
/*
    来自Thread的run方法,调用与start()之后    
*/
@Override
public void <span class="hljs-function"><span class="hljs-title">run</span></span>() {
    mTid = Process.myTid();//线程id
    Looper.prepare();//创建子线程的Looper
    synchronized (this) {
        mLooper = Looper.myLooper();//获取Looper实例
        notifyAll();// native方法,用于唤醒所有等待获取Looper的线程
    }
    Process.setThreadPriority(mPriority);//设置线程优先级
    onLooperPrepared();//上面方法的调用
    Looper.loop();//Looper开始轮询
    mTid = -1;
}

/*
    获取Looper
*/
public Looper <span class="hljs-function"><span class="hljs-title">getLooper</span></span>() {
    //判断线程是否启动
    <span class="hljs-keyword">if</span> (!isAlive()) {
        <span class="hljs-built_in">return</span> null;
    }
    
    synchronized (this) {
        <span class="hljs-keyword">while</span> (isAlive() &amp;&amp; mLooper == null) {//如果线程启动,且Looper为空
            try {
                <span class="hljs-built_in">wait</span>();//使其等待直至获取到Looper
            } catch (InterruptedException e) {
            }
        }
    }
    <span class="hljs-built_in">return</span> mLooper;
}

/*
    获取Handler
*/
@NonNull
public Handler <span class="hljs-function"><span class="hljs-title">getThreadHandler</span></span>() {
    <span class="hljs-keyword">if</span> (mHandler == null) {
        mHandler = new Handler(getLooper());
    }
    <span class="hljs-built_in">return</span> mHandler;
}


public boolean <span class="hljs-function"><span class="hljs-title">quit</span></span>() {
    Looper looper = getLooper();
    <span class="hljs-keyword">if</span> (looper != null) {
        looper.quit();
        <span class="hljs-built_in">return</span> <span class="hljs-literal">true</span>;
    }
    <span class="hljs-built_in">return</span> <span class="hljs-literal">false</span>;
}

public boolean <span class="hljs-function"><span class="hljs-title">quitSafely</span></span>() {
    Looper looper = getLooper();
    <span class="hljs-keyword">if</span> (looper != null) {
        looper.quitSafely();
        <span class="hljs-built_in">return</span> <span class="hljs-literal">true</span>;
    }
    <span class="hljs-built_in">return</span> <span class="hljs-literal">false</span>;
}


public int <span class="hljs-function"><span class="hljs-title">getThreadId</span></span>() {
    <span class="hljs-built_in">return</span> mTid;
}
复制代码
  • 注释我已写在代码上,在 HandlerThread 不使用时记得使用 getLooper().quit() 来退出这个线程,但需要注意的是 quit 和 quitSafely 的区别,接下来我将用较短的篇幅介绍一下这两个方法的区别。

quit()和 quitSafely() 的区别

HandlerThread:
public boolean quit() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quit();
            return true;
        }
        return false;
    }
public boolean <span class="hljs-function"><span class="hljs-title">quitSafely</span></span>() {
    Looper looper = getLooper();
    <span class="hljs-keyword">if</span> (looper != null) {
        looper.quitSafely();
        <span class="hljs-built_in">return</span> <span class="hljs-literal">true</span>;
    }
    <span class="hljs-built_in">return</span> <span class="hljs-literal">false</span>;
}
复制代码

Looper 在这两个方法中调用了quit()quitSafely()方法。我们点开源码查看,他们本质都是在调用MessageQueuequit方法,不同的是 quit 方法的参数不同:

Looper:

quitSafely:

public void quit() {
        mQueue.quit(true);
    }
复制代码

quit:

public void quit() {
        mQueue.quit(false);
    }
复制代码

如果大家对消息机制有所了解,那么一定知道MessageQueue是用于处理 Message(消息) 的队列,如果不知道的可以去了解一下。话不多说,接下来我们将深入MessageQueue了解一下quit(boolean safe)方法是何方神圣。

MessageQueue:
void quit(boolean safe) {
        if (!mQuitAllowed) {
            throw new IllegalStateException("Main thread not allowed to quit.");
        }
    synchronized (this) {
        <span class="hljs-keyword">if</span> (mQuitting) {
            <span class="hljs-built_in">return</span>;
        }
        mQuitting = <span class="hljs-literal">true</span>;

        <span class="hljs-keyword">if</span> (safe) {//敲黑板!这就是quitSafely和quit的区别
            removeAllFutureMessagesLocked();
        } <span class="hljs-keyword">else</span> {
            removeAllMessagesLocked();
        }

        // We can assume mPtr != 0 because mQuitting was previously false.
        nativeWake(mPtr);
    }
}
复制代码
  • 当我们在Looper中调用quitSafely()时,在MessageQueue里调用的removeAllFutureMessagesLocked()方法
  • 当我们在Looper中调用quit()时,在MessageQueue里调用的是removeAllMessagesLocked()方法
  • 而这两个方法本质的区别就是在于 remove 消息的范围,下面是一段伪代码:
            if (safe) {
                只清空队列中的延时消息(通过postDelay发送的),非延时消息继续派发,直到完成
            } else {
                移除所有消息,包括延时消息
            }
复制代码

所以说 safe 的区别就是是否清除所有消息,这两个方法的实现我们就不深究了,毕竟本文是为了讲解 HandlerThread 而不是数据结构,若有兴趣的可以去自行研究。

应用

  • IntentService的底层就是利用HandlerThread
  • 举个栗子
    Activity:
class MainActivity : AppCompatActivity() ,Handler.Callback{
private lateinit var mUIHandler :Handler
private lateinit var mDownloadThread: DownloadThread

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    <span class="hljs-built_in">set</span>ContentView(R.layout.activity_main)
    init()
}

private fun <span class="hljs-function"><span class="hljs-title">init</span></span>(){
    mUIHandler = Handler(this)

    val list = mutableListOf&lt;String&gt;()
    list.add(<span class="hljs-string">"url1"</span>)
    list.add(<span class="hljs-string">"url2"</span>)
    list.add(<span class="hljs-string">"url3"</span>)

    mDownloadThread = DownloadThread(<span class="hljs-string">"Download"</span>)
                    .setUrls(list)
                    .setUIHandler(mUIHandler)

    mDownloadThread.start()
    Log.d(<span class="hljs-string">"test"</span>,<span class="hljs-string">"开始下载"</span>)
}

override fun handleMessage(msg: Message?): Boolean {
    when(msg?.what){
        DownloadThread.START-&gt;{
            Log.d(<span class="hljs-string">"test"</span>,<span class="hljs-string">"Activity接收到了START信息"</span>)
        }
        DownloadThread.FINISH-&gt;{
            Log.d(<span class="hljs-string">"test"</span>,<span class="hljs-string">"Activity接收到了FINISH信息"</span>)
        }
    }
    <span class="hljs-built_in">return</span> <span class="hljs-literal">true</span>
}

}

复制代码

DownloadThread:

class DownloadThread(name: String?) : HandlerThread(name), Handler.Callback {
    private lateinit var mWorkHandler: Handler
    private lateinit var mUIHandler: Handler
    private lateinit var urls: List<String>
companion object {
    const val START = 1
    const val FINISH = 2
    const val KEY = <span class="hljs-string">"getUrl"</span>
}

fun <span class="hljs-built_in">set</span>UIHandler(mUIHandler: Handler): DownloadThread {
    this.mUIHandler = mUIHandler
    <span class="hljs-built_in">return</span> this
}

fun <span class="hljs-built_in">set</span>Urls(urls: List&lt;String&gt;): DownloadThread {
    this.urls = urls
    <span class="hljs-built_in">return</span> this
}

override fun <span class="hljs-function"><span class="hljs-title">onLooperPrepared</span></span>() {
    super.onLooperPrepared()
    <span class="hljs-keyword">if</span> (looper != null)
        mWorkHandler = Handler(looper, this)

    //在这里发送下载信息
    urls.forEach { url-&gt;
        val message = mWorkHandler.obtainMessage()
        val bundle = Bundle()
        bundle.putString(KEY,url)
        message.data = bundle
        mWorkHandler.sendMessage(message)
    }
}


//mWorkHandler的handleMessage
override fun handleMessage(msg: Message?): Boolean {
    <span class="hljs-keyword">if</span> (msg == null || msg.data == null) <span class="hljs-built_in">return</span> <span class="hljs-literal">false</span>

    val url = msg.data.get(KEY) as String//获取url

    val startMessage: Message = mUIHandler.obtainMessage(START)
    mUIHandler.sendMessage(startMessage)
    Log.d(<span class="hljs-string">"test"</span>,<span class="hljs-string">"<span class="hljs-variable">$url</span> :Thread发送START信息"</span>)

    Thread.sleep(2000)
    Log.d(<span class="hljs-string">"test"</span>,<span class="hljs-string">"<span class="hljs-variable">$url</span> :Thread执行耗时操作中..."</span>)

    val finishMessage: Message = mUIHandler.obtainMessage(FINISH)
    mUIHandler.sendMessage(finishMessage)
    Log.d(<span class="hljs-string">"test"</span>,<span class="hljs-string">"<span class="hljs-variable">$url</span> :Thread发送FINISH信息"</span>)
    <span class="hljs-built_in">return</span> <span class="hljs-literal">true</span>
}

}

复制代码

结果:

2019-01-30 20:47:47.743  D/test: 开始下载

2019-01-30 20:47:47.744 D/test: url1 :Thread 发送 START 信息
2019-01-30 20:47:47.776 D/test: Activity 接收到了 START 信息
2019-01-30 20:47:49.746 D/test: url1 :Thread 执行耗时操作中…
2019-01-30 20:47:49.747 D/test: url1 :Thread 发送 FINISH 信息
2019-01-30 20:47:49.747 D/test: Activity 接收到了 FINISH 信息

2019-01-30 20:47:49.747 D/test: url2 :Thread 发送 START 信息
2019-01-30 20:47:49.747 D/test: Activity 接收到了 START 信息
2019-01-30 20:47:51.748 D/test: url2 :Thread 执行耗时操作中…
2019-01-30 20:47:51.749 D/test: url2 :Thread 发送 FINISH 信息
2019-01-30 20:47:51.750 D/test: Activity 接收到了 FINISH 信息

2019-01-30 20:47:51.749 D/test: url3 :Thread 发送 START 信息
2019-01-30 20:47:51.750 D/test: Activity 接收到了 START 信息
2019-01-30 20:47:53.750 D/test: url3 :Thread 执行耗时操作中…
2019-01-30 20:47:53.751 D/test: url3 :Thread 发送 FINISH 信息
2019-01-30 20:47:53.751 D/test: Activity 接收到了 FINISH 信息

复制代码
总结

上面就是利用HandlerThread在子线程中执行串行任务,并反馈到主线程的栗子。总的来说 HandlerThread 的知识点就是这些,若有错误或者遗漏欢迎指出。

  • Android

    开放手机联盟(一个由 30 多家科技公司和手机公司组成的团体)已开发出 Android,Android 是第一个完整、开放、免费的手机平台。

    293 引用
感谢    赞同    分享    收藏    关注    反对    举报    ...