編輯:關於 Android 程式設計
要真正理解 Android 的執行緒間通訊機制,最好的方式就是直接閱讀源碼。本文以 HandlerThread 為切入點,循序剖析 Handler、Looper 與 MessageQueue 三者之間的關係。
HandlerThread 是 Android 系統提供的一個類別,它繼承自 Thread,本質上就是一個帶有消息迴圈能力的執行緒。來看它的 run 方法:
public void run() {
mTid = Process.myTid();
Looper.prepare(); // #1
synchronized (this) {
mLooper = Looper.myLooper(); // #2
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop(); // #3
mTid = -1;
}
在第 1 個標記處,呼叫了 Looper 的 prepare 方法:
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)); // #4
}
第 4 個標記處把 Looper 實例存進 ThreadLocal(執行緒局部變數),將 Looper 與當前執行緒綁定。第 2 個標記處則取得與當前執行緒綁定的 Looper 實例,讓該執行緒擁有 Looper。第 3 個標記處呼叫 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;
}
msg.target.dispatchMessage(msg);
msg.recycle();
}
}
loop() 方法的作用,是從 Looper 中取得 MessageQueue 佇列,再從中一個個取出 Message,透過對應的 Handler 分發出去,直到取完為止。那麼當訊息取完後,執行緒在哪裡被喚醒並繼續循環呢?答案是:在呼叫 Handler 的 sendMessage 向 MessageQueue 插入訊息時,會呼叫本地方法 nativeWake(mPtr) 來喚醒它。
最常見的用法,是在 Activity 中建立一個 Handler 物件來更新 UI:
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
來看 Handler 的建構方法:
public Handler() {
this(null, false);
}
public Handler(Callback callback, boolean async) {
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
可以看到,在建構方法中,Handler 已經取得了當前執行緒的 Looper 實例,以及該 Looper 的 MessageQueue 佇列。
講到這裡,三者之間的關係已經清晰明瞭:Handler 發送訊息的本質,其實就是往 MessageQueue 佇列中插入訊息。
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
if (queue == null) {
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
而 Handler 的 enqueueMessage 最終會呼叫 MessageQueue 的 enqueueMessage:
final boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new AndroidRuntimeException("Message must have a target.");
}
boolean needWake;
synchronized (this) {
if (mQuiting) {
return false;
}
msg.when = when;
Message p = mMessages;
if (p == null || when == 0 || when < p.when) {
// 新的表頭,若佇列被阻塞則喚醒
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
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;
prev.next = msg;
}
}
if (needWake) {
nativeWake(mPtr); // #5
}
return true;
}
在第 5 個標記處呼叫的 nativeWake(mPtr) 是一個本地方法,用於喚醒阻塞中的執行緒。
總結來說:每個執行緒透過 Looper 綁定一個 MessageQueue,Handler 負責把 Message 投遞到佇列中,再由 Looper 的迴圈不斷取出並分發。執行緒間的通訊,正是藉由這套「共用佇列 + 訊息分發」的機制得以實現。
動手寫一個自己的 Android 第三方庫
Android Studio 的出現大幅簡化了開發流程,今天來談談怎麼打造屬於自己的庫。路徑很簡單:File → New Module → Android Library
Android 廣告輪播圖實作:自定義 ViewPager 變換動畫與自動循環播放
本文示範一個完整的首頁廣告輪播方案,特色是使用了自定義的 ViewPager 子類來實現切換時的縮放堆疊動畫,並搭配 Handler 計時器完成自動循環。 版面配置
Android SurfaceView 實戰:打造精美抽獎轉盤
一、概述 今天為大家帶來一個 SurfaceView 的實戰案例。自定義 View 寫過不少,卻一直沒寫過 SurfaceView。它是個什麼東西?什麼時候用它比較合適
Android 讀取 assets 與 raw 檔案內容實作
Android 專案中有兩種常見的唯讀資源位置:assets 與 res/raw。assets 不一定要副檔名,也不會自動產生資源 ID;raw 則會在 res 目錄下建