新聞中心
我們?cè)谌粘i_發(fā)中,總是不可避免的會(huì)用到 handler,雖說(shuō) Handler 機(jī)制并不等同于 Android 的消息機(jī)制,但 Handler 的消息機(jī)制在 Android 開發(fā)中早已諳熟于心,非常重要!

通過(guò)本文,你可以非常容易得到一下問(wèn)題的答案:
- Handler、Looper、Message 和 MessageQueue 的原理以及它們之間的關(guān)系到底是怎樣的?
- MessageQueue 存儲(chǔ)結(jié)構(gòu)是什么?
- 子線程為啥一定要調(diào)用 Looper.prepare() 和 Looper.loop()?
Handler 的簡(jiǎn)單使用
相信應(yīng)該沒(méi)有人不會(huì)使用 Handler 吧?假設(shè)在 Activity 中處理一個(gè)耗時(shí)任務(wù),需要更新 UI,簡(jiǎn)單看看我們平時(shí)是怎么處理的。
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_main3)
- // 請(qǐng)求網(wǎng)絡(luò)
- subThread.start()
- }
- override fun onDestroy() {
- subThread.interrupt()
- super.onDestroy()
- }
- private val handler by lazy(LazyThreadSafetyMode.NONE) { MyHandler() }
- private val subThread by lazy(LazyThreadSafetyMode.NONE) { SubThread(handler) }
- private class MyHandler : Handler() {
- override fun handleMessage(msg: Message) {
- super.handleMessage(msg)
- // 主線程處理邏輯,一般這里需要使用弱引用持有 Activity 實(shí)例,以免內(nèi)存泄漏
- }
- }
- private class SubThread(val handler: Handler) : Thread() {
- override fun run() {
- super.run()
- // 耗時(shí)操作 比如做網(wǎng)絡(luò)請(qǐng)求
- // 網(wǎng)絡(luò)請(qǐng)求完畢,咱們就得嘩嘩嘩通知 UI 刷新了,直接直接考慮 Handler 處理,其他方案暫時(shí)不做考慮
- // 第一種方法,一般這個(gè) data 是請(qǐng)求結(jié)果解析的內(nèi)容
- handler.obtainMessage(1,data).sendToTarget()
- // 第二種方法
- val message = Message.obtain() // 盡量使用 Message.obtain() 初始化
- message.what = 1
- message.obj = data // 一般這個(gè) data 是請(qǐng)求結(jié)果解析的內(nèi)容
- handler.sendMessage(message)
- // 第三種方法
- handler.post(object : Thread() {
- override fun run() {
- super.run()
- // 處理更新操作
- }
- })
- }
- }
上述代碼非常簡(jiǎn)單,因?yàn)榫W(wǎng)絡(luò)請(qǐng)求是一個(gè)耗時(shí)任務(wù),所以我們新開了一個(gè)線程,并在網(wǎng)絡(luò)請(qǐng)求結(jié)束解析完畢后通過(guò) Handler 來(lái)通知主線程去更新 UI,簡(jiǎn)單采用了 3 種方式,細(xì)心的小伙伴可能會(huì)發(fā)現(xiàn),其實(shí)第一種和第二種方法是一樣的。就是利用 Handler 來(lái)發(fā)送了一個(gè)攜帶了內(nèi)容 Message 對(duì)象,值得一提的是:我們應(yīng)該盡可能地使用 Message.obtain() 而不是 new Message() 進(jìn)行 Message 的初始化,主要是 Message.obtain() 可以減少內(nèi)存的申請(qǐng)。
受到大家在前面文章提出的建議,我們就盡量地少貼一些源碼了,大家可以直接很容易發(fā)現(xiàn),上述的所有方法最終都會(huì)調(diào)用這個(gè)方法:
- public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
- MessageQueue queue = mQueue;
- if (queue == null) {
- RuntimeException e = new RuntimeException(
- this + " sendMessageAtTime() called with no mQueue");
- Log.w("Looper", e.getMessage(), e);
- return false;
- }
- return enqueueMessage(queue, msg, uptimeMillis);
- }
- private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
- msg.target = this;
- if (mAsynchronous) {
- msg.setAsynchronous(true);
- }
- return queue.enqueueMessage(msg, uptimeMillis);
- }
上面的代碼出現(xiàn)了一個(gè) MessageQueue,并且最終調(diào)用了 MessageQueue#enqueueMessage 方法進(jìn)行消息的入隊(duì),我們不得不簡(jiǎn)單說(shuō)一下 MessageQueue 的基本情況。
MessageQueue
顧名思義,MessageQueue 就是消息隊(duì)列,即存放多條消息 Message 的容器,它采用的是單向鏈表數(shù)據(jù)結(jié)構(gòu),而非隊(duì)列。它的 next() 指向鏈表的下一個(gè) Message 元素。
- boolean enqueueMessage(Message msg, long when) {
- // ... 省略一些檢查代碼
- synchronized (this) {
- // ... 省略一些檢查代碼
- msg.markInUse();
- msg.when = when;
- Message p = mMessages;
- boolean needWake;
- if (p == null || when == 0 || when < p.when) {
- // New head, wake up the event queue if blocked.
- msg.next = p;
- mMessages = msg;
- needWake = mBlocked;
- } else {
- // Inserted within the middle of the queue. Usually we don't have to wake
- // up the event queue unless there is a barrier at the head of the queue
- // and the message is the earliest asynchronous message in the queue.
- needWake = mBlocked && p.target == null && msg.isAsynchronous();
- Message prev;
- for (;;) {
- prev = p;
- p = p.next;
- if (p == null || when < p.when) {
- break;
- }
- if (needWake && p.isAsynchronous()) {
- needWake = false;
- }
- }
- msg.next = p; // invariant: p == prev.next
- prev.next = msg;
- }
- // We can assume mPtr != 0 because mQuitting is false.
- if (needWake) {
- nativeWake(mPtr);
- }
- }
- return true;
- }
從入隊(duì)消息 enqueueMessage() 的實(shí)現(xiàn)來(lái)看,它的主要操作其實(shí)就是單鏈表的插入操作,這里就不做過(guò)多的解釋了,我們可能應(yīng)該更多的關(guān)心它的出隊(duì)操作方法 next():
- Message next() {
- // ...
- int nextPollTimeoutMillis = 0;
- for (;;) {
- // ...
- nativePollOnce(ptr, nextPollTimeoutMillis);
- synchronized (this) {
- // Try to retrieve the next message. Return if found.
- final long now = SystemClock.uptimeMillis();
- Message prevMsg = null;
- Message msg = mMessages;
- if (msg != null && msg.target == null) {
- // Stalled by a barrier. Find the next asynchronous message in the queue.
- do {
- prevMsg = msg;
- msg = msg.next;
- } while (msg != null && !msg.isAsynchronous());
- }
- if (msg != null) {
- if (now < msg.when) {
- // Next message is not ready. Set a timeout to wake up when it is ready.
- nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
- } else {
- // Got a message.
- mBlocked = false;
- if (prevMsg != null) {
- prevMsg.next = msg.next;
- } else {
- mMessages = msg.next;
- }
- msg.next = null;
- if (DEBUG) Log.v(TAG, "Returning message: " + msg);
- msg.markInUse();
- return msg;
- }
- } else {
- // No more messages.
- nextPollTimeoutMillis = -1;
- }
- //...
- }
- //...
- // While calling an idle handler, a new message could have been delivered
- // so go back and look again for a pending message without waiting.
- nextPollTimeoutMillis = 0;
- }
- }
next() 方法其實(shí)很長(zhǎng),不過(guò)我們僅僅貼了極少的一部分,可以看到,里面不過(guò)是有一個(gè) for (;;) 的無(wú)限循環(huán),循環(huán)體內(nèi)部調(diào)用了一個(gè) nativePollOnce(long, int) 方法。這是一個(gè) Native 方法,實(shí)際作用是通過(guò) Native 層的 MessageQueue 阻塞當(dāng)前調(diào)用棧線程 nextPollTimeoutMillis 毫秒的時(shí)間。
下面是 nextPollTimeoutMillis 取值的不同情況的阻塞表現(xiàn):
- 小于 0,一直阻塞,直到被喚醒;
- 等于 0,不會(huì)阻塞;
- 大于 0,最長(zhǎng)阻塞 nextPollTimeoutMillis 毫秒,期間如被喚醒會(huì)立即返回。
可以看到,最開始 nextPollTimeoutMillis 的初始化值是 0,所以不會(huì)阻塞,會(huì)直接去取 Message 對(duì)象,如果沒(méi)有取到 Message 對(duì)象數(shù)據(jù),則直接會(huì)把 nextPollTimeoutMillis 置為 -1,此時(shí)滿足小于 0 的條件,會(huì)被一直阻塞,直到其他地方調(diào)用另外一個(gè) Native 方法 nativeWake(long) 進(jìn)行喚醒。如果取到值的話,會(huì)直接把得到的 Message 對(duì)象進(jìn)行返回。
原來(lái),nativeWake(long) 方法在前面的 MessageQueue#enqueueMessage 方法有個(gè)調(diào)用,調(diào)用時(shí)機(jī)是在 MessageQueue 入隊(duì)消息的過(guò)程中。
現(xiàn)在已經(jīng)知道:Handler 發(fā)送了 Message,消息用 MessageQueue 進(jìn)行存儲(chǔ),使用 MessageQueue#enqueueMessage 方法進(jìn)行入隊(duì),使用 MessageQueue#next 方法進(jìn)行輪訓(xùn)消息。這就不免拋出了一個(gè)問(wèn)題,MessageQueue#next 方法是誰(shuí)調(diào)用的?沒(méi)錯(cuò),就是 Looper。
Looper
Looper 在 Android 的消息機(jī)制中扮演著消息循環(huán)的角色,具體來(lái)說(shuō)就是它會(huì)不停地從 MessageQueue 通過(guò) next() 查看是否有新消息,如果有新消息就立刻處理,否則就任由 MessageQueue 阻塞在那里。
我們直接看看 Looper 最重要的方法:loop():
- public static void loop() {
- final Looper me = myLooper();
- if (me == null) {
- throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
- }
- // ...
- for (;;) {
- Message msg = queue.next(); // might block
- if (msg == null) {
- // No message indicates that the message queue is quitting.
- return;
- }
- //...
- try {
- // 分發(fā)消息給 handler 處理
- msg.target.dispatchMessage(msg);
- dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
- } finally {
- // ...
- }
- // ...
- }
- }
方法省去了大量的代碼,只保留了核心邏輯??梢钥吹剑紫葧?huì)通過(guò) myLooper() 方法得到 Looper 對(duì)象,如果這個(gè) Looper 返回為空的話,則直接拋出異常。否則進(jìn)入到一個(gè) for (;;) 循環(huán)中,調(diào)用 MessageQueue#next() 方法進(jìn)行輪訓(xùn)獲取 Message 對(duì)象,如果獲取的 Message 對(duì)象為空,則直接退出 loop() 方法。否則直接通過(guò) msg.target 拿到 Handler 對(duì)象,并調(diào)用 Handler#dispatchMessage() 方法。
我們先來(lái)看看Handler#dispatchMessage() 方法實(shí)現(xiàn):
- public void dispatchMessage(Message msg) {
- if (msg.callback != null) {
- handleCallback(msg);
- } else {
- if (mCallback != null) {
- if (mCallback.handleMessage(msg)) {
- return;
- }
- }
- handleMessage(msg);
- }
- }
- private static void handleCallback(Message message) {
- message.callback.run();
- }
代碼比較簡(jiǎn)單,如果 Message 設(shè)置了 callback 則,直接調(diào)用 message.callback.run(),否則判斷是否初始化了 `m
再來(lái)看看 myLooper() 方法:
- public static @Nullable Looper myLooper() {
- return sThreadLocal.get();
- }
看看 sThreadLocal 是什么:
- static final ThreadLocal sThreadLocal = new ThreadLocal();
這個(gè) ThreadLocal 是什么呢?
ThreadLocal
關(guān)于 ThreadLocal,我們直接采取 嚴(yán)振杰文章 中的內(nèi)容。
看到 ThreadLocal 的第一感覺(jué)就是該類和線程有關(guān),確實(shí)如此,但是要注意它不是線程,否則它就該叫 LocalThread 了。
ThreadLocal 是用來(lái)存儲(chǔ)指定線程的數(shù)據(jù)的,當(dāng)某些數(shù)據(jù)的作用域是該指定線程并且該數(shù)據(jù)需要貫穿該線程的所有執(zhí)行過(guò)程時(shí)就可以使用 ThreadnLocal 存儲(chǔ)數(shù)據(jù),當(dāng)某線程使用 ThreadnLocal 存儲(chǔ)數(shù)據(jù)后,只有該線程可以讀取到存儲(chǔ)的數(shù)據(jù),除此線程之外的其他線程是沒(méi)辦法讀取到該數(shù)據(jù)的。
一些讀者看完上面這段話應(yīng)該還是不理解 ThreadLocal 的作用,我們舉個(gè)栗子:
- ThreadLocal
local = new ThreadLocal<>(); - // 設(shè)置初始值為true.
- local.set(true);
- Boolean bool = local.get();
- Logger.i("MainThread讀取的值為:" + bool);
- new Thread() {
- @Override
- public void run() {
- Boolean bool = local.get();
- Logger.i("SubThread讀取的值為:" + bool);
- // 設(shè)置值為false.
- local.set(false);
- }
- }.start():
- // 主線程睡1秒,確保上方子線程執(zhí)行完畢再執(zhí)行下面的代碼。
- Thread.sleep(1000);
- Boolean newBool = local.get();
- Logger.i("MainThread讀取的新值為:" + newBool);
代碼沒(méi)什么好說(shuō)的吧,打印出來(lái)的日志,你會(huì)看到是這樣的:
- MainThread讀取的值為:trueSubThread讀取的值為:nullMainThread讀取的值為:true
第一條 Log 無(wú)可置疑,因?yàn)樵O(shè)置了值為 true,因?yàn)榇蛴〗Y(jié)果沒(méi)什么好說(shuō)的。對(duì)于第二條 Log,根據(jù)上方介紹,某線程使用 ThreadLocal 存儲(chǔ)的數(shù)據(jù),只能被該線程讀取,因此第二條 Log 的結(jié)果是:null。緊接著在子線程中設(shè)置了 ThreadLocal 的值為 false,然后第三條 Log 將被打印,原理同上,子線程中設(shè)置了 ThreadLocal 的值并不影響主線程的數(shù)據(jù),所以打印是 true。
實(shí)驗(yàn)結(jié)果證實(shí):就算是同一個(gè) ThreadLocal 對(duì)象,任一線程對(duì)其的 set() 和 get() 方法的操作都是相互獨(dú)立互不影響的。
Looper.myLooper()
我們回到 Looper.myLooper():
- static final ThreadLocal
sThreadLocal = new ThreadLocal ();
我們看看是在哪兒對(duì) sThreadLocal 操作的。
- public static void prepare() {
- prepare(true);
- }
- private static void prepare(boolean quitAllowed) {
- if (sThreadLocal.get() != null) {
- throw new RuntimeException("Only one Looper may be created per thread");
- }
- sThreadLocal.set(new Looper(quitAllowed));
- }
所以知道了吧,這就是在子線程中使用 Handler 前,必須要調(diào)用 Looper.prepare() 的原因。
可能你會(huì)疑問(wèn),我在主線程使用的時(shí)候,沒(méi)有要求 Looper.prepare() 呀。
原來(lái),我們?cè)?ActivityThread 中,有去顯示調(diào)用 Looper.prepareMainLooper():
- public static void main(String[] args) {
- // ...
- Looper.prepareMainLooper();
- // ...
- if (sMainThreadHandler == null) {
- sMainThreadHandler = thread.getHandler();
- }
- //...
- Looper.loop();
- // ...
- }
我們看看 Looper.prepareMainLooper():
- public static void prepareMainLooper() {
- prepare(false);
- synchronized (Looper.class) {
- if (sMainLooper != null) {
- throw new IllegalStateException("The main Looper has already been prepared.");
- }
- sMainLooper = myLooper();
- }
- }
網(wǎng)站題目:Android消息機(jī)制Handler,有必要再講一次
網(wǎng)站路徑:http://www.5511xx.com/article/dhgehso.html


咨詢
建站咨詢
