編輯:關於 Android 程式設計
上一篇講了更新 UI 的方法與見解,接著談了線程檢查機制。本篇則深入分析更新 UI 的核心——Android 的消息系統模型。這個話題其實已不再局限于更新 UI 的範疇,但非常值得學習。需要說明的是,網上相關講解很多,本文是綜合整理並融入個人理解加以概括,也歡迎造詣更深的朋友批評指正。
Android 消息機制主要有以下幾個要點:
1. Handler 調度消息和 Runnable 對象在不同線程中執行相應動作。
2. Looper 消息泵,為一個線程開啟消息循環。
3. MessageQueue 遵循 FIFO 先進先出規則的消息隊列,以鏈表形式存取 Message,供 Looper 提取。
借用一張模型圖來綜合理解:

整體流程如下:
1. 在該線程中初始化 Looper 並 prepare(准備):
Looper.prepare(); //稍微有點兒多,詳細見下文
2. 定義一個處理消息的 Handler:
handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); //處理邏輯 } };
3. 啟動 Looper 並開始輪詢消息:
Looper.loop(); //詳細見下文 //要停止的話,使用Looper.quit();
4. 在其他線程將數據或回調對象以 Message 形式通過 Handler 發至消息隊列:
handler.sendMessage(msg)
5. Looper 的 loop() 從隊列取到消息並喚醒處理邏輯:
//即loop()方法中的代碼 for (;;) { //顯然這個死循環一直在等待消息到來並處理 Message msg = queue.next(); // 取一條消息 if (msg == null) { return; } msg.target.dispatchMessage(msg); //調用消息綁定的handler執行處理邏輯 //other code.... }
6. Handler 跳轉到執行處理邏輯的過程:
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(); }
當 ActivityManagerService 為應用創建新進程並啟動 Activity 時,主線程 ActivityThread 首先被創建。該進程會加載執行 ActivityThread 的靜態成員函數 main:
public static void main(String[] args) { //other code.. 我們只看有用的部分,其他暫略過 Looper.prepareMainLooper(); //准備looper,注,綁定的為當前主線程 ActivityThread thread = new ActivityThread();//開啟一個新ActivityThread線程 thread.attach(false);//最後執行到activity //other code.. Looper.loop(); //啟動looper
這個靜態函數做了兩件事:在主線程中創建 ActivityThread 實例,並通過 Looper 使主線程進入消息循環。隨後代碼經過一系列邏輯最終調用 Activity 的 attach 方法。打開 Activity 類,可以看到它定義了 uiThread 與 Handler 參數:
ActivityThread mMainThread;//對應上邊的ActivityThread線程 private Thread mUiThread;//主Ui線程 final Handler mHandler = new Handler();//這個handler就是activity用來處理Ui的了。我們自己定義的handler其實等於重新定義了這個mHandler;
Activity 的 attach 方法中,把當前主線程賦給 mUiThread,把 ActivityThread 賦給 mMainThread。所以更新 UI 時都會用到 sendMessage,比如 runOnUiThread:
public final void runOnUiThread(Runnable action) { /** *如果當前線程不為Ui主線程則使用定義好的mHandler */ if (Thread.currentThread() != mUiThread) { mHandler.post(action); } else { action.run(); } }
打開 post 方法:
public final boolean post(Runnable r) { return sendMessageDelayed(getPostMessage(r), 0); }
依然是熟悉的配方——封裝成消息然後發送出去。回顧第一篇的四種方法:new 一個 handler 來 sendMessage;用 handler 來 post;runOnUiThread;view.post,本質上都是通過某個 mHandler 發送消息。以 view.post 為例:
public boolean post(Runnable action) { final AttachInfo attachInfo = mAttachInfo; if (attachInfo != null) { return attachInfo.mHandler.post(action); } // Assume that post will succeed later ViewRootImpl.getRunQueue().post(action); return true; }
可見整個 UI 更新機制其實就是 Android 消息系統模型的一個簡單實現。作為補充,下面再從源碼層面完整過一遍這個模型。
public final class Message implements Parcelable { //繼承Parcelable 用於數據傳遞 /**幾種數據類型**/ public int arg1; public int arg2; public Object obj; Bundle data; public int what;//供handler處理的消息識別標識身份 long when;//什麼時候處理該消息 Handler target;//處理該消息的目標handler Runnable callback; //回調方法 int flags;//標簽標識 static final int FLAG_IN_USE = 1 << 0;//是否可用(回收利用) static final int FLAG_ASYNCHRONOUS = 1 << 1; static final int FLAGS_TO_CLEAR_ON_COPY_FROM = FLAG_IN_USE; public Messenger replyTo;//可選對象,可以用來記錄發送方或接收者 Message next;//這條消息的下一條消息 /** *開一個消息池,便於循環利用消息,避免生成新對象並分配內存 */ private static final Object sPoolSync = new Object(); private static Message sPool; private static int sPoolSize = 0; private static final int MAX_POOL_SIZE = 50; }
談到消息池,就不得不看 obtain() 方法,它通過複用對象來節省內存資源:
/** *從消息池中返回一個新的消息實例,避免我們通常情況下分配新對象。 */ public static Message obtain() { synchronized (sPoolSync) { if (sPool != null) { Message m = sPool; sPool = m.next; m.next = null; sPoolSize--; return m; } } return new Message(); }
基於此方法還有一系列重載,先取消息再賦值傳參:
public static Message obtain(Handler h, int what, int arg1, int arg2, Object obj) { Message m = obtain(); m.target = h; m.what = what; m.arg1 = arg1; m.arg2 = arg2; m.obj = obj; return m; } //調用obtain並賦值,不再一一列出 public static Message obtain(Handler h) {//..} public static Message obtain(Handler h, Runnable callback) {//..} public static Message obtain(Handler h, int what) {//...} public static Message obtain(Handler h, int what, Object obj) {//...} public static Message obtain(Handler h, int what, int arg1, int arg2) {//...}
用完後通過 recycle 回收進消息池:
public void recycle() { clearForRecycle(); synchronized (sPoolSync) { if (sPoolSize < MAX_POOL_SIZE) { next = sPool; sPool = this; sPoolSize++; } } } //清空所有數據 void clearForRecycle() { flags = 0; what = 0; arg1 = 0; arg2 = 0; obj = null; replyTo = null; when = 0; target = null; callback = null; data = null; }
public class Looper { private static final String TAG = Looper; static final ThreadLocal sThreadLocal = new ThreadLocal(); private static Looper sMainLooper;//唯一對應一個主線程的looper靜態實例 final MessageQueue mQueue;//消息隊列 final Thread mThread; //當前綁定線程 volatile boolean mRun; //是否允許退出 private Printer mLogging;//日志打印 //....各種方法體.... }
ThreadLocal 為每個線程提供獨立的存儲空間,方便地為一個線程定義唯一對應的 Looper 實例,可簡單理解為只作用於當前線程的 new Looper。其構造方法是私有的,通過單例模式保證外部從該線程取得唯一 Looper:
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mRun = true; mThread = Thread.currentThread(); } //重載,主要看下邊的prepare(boolean quitAllowed)方法 public static void prepare() { prepare(true); } 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));//在線程中初始化一個實例 }
prepareMainLooper 與 getMainLooper 則負責初始化並獲取應用主線程的 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.); } final MessageQueue queue = me.mQueue; Binder.clearCallingIdentity(); final long ident = Binder.clearCallingIdentity(); //開始循環取消息操作 for (;;) { Message msg = queue.next(); //取下一條消息 if (msg == null) { // 如果消息隊列沒有消息則掛起 return; } Printer logging = me.mLogging; if (logging != null) { logging.println(>>>>> Dispatching to + msg.target + + msg.callback + : + msg.what); } //調用消息處理邏輯(回調和執行handler處理) msg.target.dispatchMessage(msg); //回收消息 msg.recycle(); } }
至此,Android 消息系統模型的核心——Message、Looper 便梳理完畢,MessageQueue 與 Handler 的細節讀者可結合源碼自行深入研究。
Android 四大跨進程通訊方式解析:Activity、ContentProvider、Broadcast 與 AIDL Service
為何需要跨進程通訊 Android 應用之間預設無法直接共享記憶體,因此需要透過系統提供的機制交換資料。常見方式包括 Activity、ContentProvider、B
Android 手機耗電太快?先從這幾個地方查起
Android 5.0 推出後,有相當多使用者反映設備的電量掉得特別快。原版 Lollipop 確實存在 Wi-Fi 造成異常耗電的問題,但這部分已在 Android 5
Android 學習筆記之 ImageView 的 scaleType 屬性詳解
我們知道,ImageView 有一個屬性叫做 scaleType,它的取值一共有八種,分別是:matrix、fitXY、fitStart、fitCenter、fitEnd
Android Service 全面解析:分類、生命週期與實戰要點
Service 是 Android 四大組件之一,也是最容易被誤解的組件。本文將從分類、與 Thread 的區別、生命週期,到實際開發中的綁定、前台服務與常見配置,做一次