Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

Android 消息機制核心知識全解析:Looper、Handler、Message 與 MessageQueue

編輯:Android 資訊

消息機制幾乎是每次 Android 面試都繞不開的考點。但學習它的意義遠不止於應對面試——在日常開發中,它扮演著舉足輕重的角色,真正理解其運作原理至關重要。下面就從最基礎的概念說起。

Looper

核心作用:

  • 與線程進行關聯
  • 循環取出並分發消息

1、Looper 能否直接實例化?

Looper 的構造方法是私有的,內部主要完成兩件事:創建一個 MessageQueue,以及記錄當前所屬的 Thread。

 private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }

2、一個線程能對應多個 Looper 嗎?

不能。一個線程只能對應一個 Looper,這由 ThreadLocal 來保證。若重複調用 Looper.prepare(),將拋出運行時異常。

 private static void prepare(boolean quitAllowed) { if (sThreadLocal.get() != null) { // 檢查是否已有 Looper 與當前線程關聯 throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper(quitAllowed)); }

3、Looper 是無限循環,會阻塞嗎?

會。開啟 loop 後本質上是一個死循環,不斷從 MessageQueue 中取出並處理消息;不過它也存在退出機制——當隊列中沒有消息且收到退出信號時,循環便會結束。

 public static void loop() { final Looper me = myLooper(); if (me == null) { throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } final MessageQueue queue = me.mQueue; // 略 for (;;) { Message msg = queue.next(); // might block if (msg == null) { // 沒有消息時退出循環 return; } // 略 msg.target.dispatchMessage(msg); }

4、能否再次調用 Looper.prepareMainLooper?

不可以。prepareMainLooper 最終也是調用 prepare(),原因同第 2 點。

public static void prepareMainLooper() { prepare(false); // 創建 Looper synchronized (Looper.class) { if (sMainLooper != null) { throw new IllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); } }

5、MainLooper 是什麼時候創建的?

MainLooper 在啟動 Activity、創建 ActivityThread(注意它並不是一個 Thread)時被創建,因此無法重複創建。

public static void main(String[] args) { // 略 Process.setArgV0("<pre-initialized>"); Looper.prepareMainLooper(); // 略 ActivityThread thread = new ActivityThread(); thread.attach(false); // 略 if (sMainThreadHandler == null) { sMainThreadHandler = thread.getHandler(); } // 略 Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); } }

Handler

核心作用:

  • 向 MessageQueue 發送消息
  • 處理消息

1、Handler 如何與 Looper、MessageQueue 關聯起來?

一個 Looper 對應一個線程,並包含一個 MessageQueue。當我們創建 Handler 時,會先從當前線程取出對應的 Looper,再從 Looper 中取得 MessageQueue。

// 1、自動獲取 public Handler(Callback callback, boolean async) { // 略 mLooper = Looper.myLooper(); // 取出當前線程中的 Looper if (mLooper == null) { throw new RuntimeException( "Can't create handler inside thread that has not called Looper.prepare()"); } mQueue = mLooper.mQueue; // 取出 MessageQueue mCallback = callback; mAsynchronous = async; } // 2、傳入一個 Looper public Handler(Looper looper, Callback callback, boolean async) { mLooper = looper; mQueue = looper.mQueue; mCallback = callback; mAsynchronous = async; }

Message

數據結構為單項鏈表。

核心作用:

  • 作為數據的載體

1、消息是如何複用的?

通過一個全局的消息池(鏈表結構)來實現複用。

public static Message obtain() { synchronized (sPoolSync) { if (sPool != null) { Message m = sPool; sPool = m.next; m.next = null; m.flags = 0; // 清除 in-use 標記 sPoolSize--; return m; } } return new Message(); }

2、Message 為什麼能夠傳遞?

在 Android 中傳遞對象需要實現 Serializable 或 Parcelable 接口,而 Message 實現了 Parcelable。

public final class Message implements Parcelable { // 略 }

3、如何與 Handler 關聯?

在消息傳遞機制中,Handler 扮演著「快遞員」的角色,那麼它又是如何與「貨物」——Message 建立聯繫的呢?其實 Message 有一個類型為 Handler 的成員變量 target。

/*package*/ Runnable callback; public int arg1; public int arg2; public Object obj; /*package*/ Handler target; // 關鍵點

當我們通過 Handler 發送一個 Message 時,最終都會將 target 賦值為 this,即當前這個 Handler。

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; // 賦值語句 if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }

此外,若通過 Message.obtain() 獲取複用消息,同樣會完成賦值。順帶一提,Handler.obtainMessage() 內部調用的正是 Message.obtain()。

public final Message obtainMessage(){ return Message.obtain(this); }

總結

通過一系列包含關係,Looper、Handler、Message、MessageQueue 彼此關聯,形成一個閉環,從而開啟消息循環。

一些值得深入的困惑

在學習這部分知識的過程中,由於能力有限,仍有一些問題值得進一步探討。若你對下面的問題有更好的理解,歡迎交流指正。

1、Message 中的 sPool 在哪裡初始化?為什麼 Message.obtain() 不會拋異常?

2、ActivityThread 並不是線程,為什麼能創建 Looper?Main Thread 又是何時創建的?

3、為什麼序列化後的對象就能傳遞?是否與 Binder 有關?

4、MessageQueue 對應的是 NativeMessageQueue,其底層實現值得進一步學習。

5、Looper.loop() 會退出嗎?退出的時機是什麼?若會退出,主線程是否也會隨之退出?

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved