編輯:關於 Android 程式設計
Looper.prepare()。Parcelable 的派生類,包含 what、arg1、arg2、obj 等字段。
public final class Looper {
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper;
final MessageQueue mQueue;
final Thread mThread;
public static void prepare() { ... }
private static void prepare(boolean quitAllowed) { ... }
public static void prepareMainLooper() { ... }
public static Looper getMainLooper() { ... }
public static Looper myLooper() { ... }
public static void loop() { ... }
}
public final class MessageQueue {
Message next() { ... }
boolean enqueueMessage(Message msg, long when) { ... }
}
public final class Message implements Parcelable {
public int what;
public int arg1;
public int arg2;
public Object obj;
public Messenger replyTo;
private static Message sPool; // 消息池鏈表頭
private static int sPoolSize = 0;
private static final int MAX_POOL_SIZE = 50;
public static Message obtain() { ... }
public void sendToTarget() { ... }
void recycleUnchecked() { ... }
}
ThreadLocal 即「線程本地變量」。把數據放進 ThreadLocal 後,每個線程都會持有該變量的一份獨立副本,從根本上避免並發訪問的線程安全問題。Looper 正是用它來保證「每個線程各自持有自己的 Looper 實例」。
因為 ActivityThread.main() 已經調用了 Looper.prepareMainLooper():
public static void main(String[] args) {
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException(
"The main Looper has already been prepared");
}
sMainLooper = myLooper();
}
}
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));
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
從這段代碼可以得出兩個結論:一個線程只能有一個 Looper 對象;同一線程中 prepare() 系列方法最多調用一次,重複調用會拋異常。子線程調用的 Looper.prepare() 內部也是 prepare(true)。
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;
}
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
構造器做了三件事:取得當前線程的 Looper(取不到就拋異常,這正是「必須先 prepare」的原因)、關聯該 Looper 的 MessageQueue、保存 Callback 與 async 標誌。
dispatchMessage 揭示了消息的三條處理路徑:優先執行 Message 自帶的 Runnable(callback 字段);其次執行構造時傳入的 Callback 接口;最後才是我們最熟悉的 handleMessage()。
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(); // 沒有消息時阻塞在這裡
if (msg == null) {
return; // 隊列退出,循環結束
}
msg.target.dispatchMessage(msg);
msg.recycleUnchecked(); // 處理完後回收進消息池
}
}
loop() 是一個死循環,不斷從隊列取消息。關鍵在 msg.target.dispatchMessage(msg)——target 就是發送該消息的 Handler,因此消息由哪個 Handler 發出,就由哪個 Handler 處理。Message.sendToTarget() 的本質也是 target.sendMessage(this)。
各個 send 變體最終都彙集到 enqueueMessage:
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) {
// 時間最小,直接插入頭部
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// 否則遍歷找到合適位置插入
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;
}
}
return true;
}
MessageQueue 本質是一個按 when 字段升序排列的單鏈表,mMessages 為頭節點。插入時先判斷是否比頭節點更早,若是則直接頭插;否則遍歷找到第一個比自己晚的節點插入。延遲消息正是依靠 when = now + delayMillis 來實現的。
在 A 線程創建 Handler 並調用 loop() 進入循環等待;B 線程通過該 Handler 的 sendMessage() 把消息放入 A 線程的 MessageQueue;A 線程的 loop 循環取到消息並調用 dispatchMessage——此時的執行線程就是 A。線程切換由此完成。
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0;
sPoolSize--;
return m;
}
}
return new Message();
}
void recycleUnchecked() {
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
消息池是一個上限 50 的單鏈表。處理完的消息通過頭插法放回池中,下次 obtain() 直接複用,避免頻繁創建對象帶來的 GC 壓力。因此推薦使用 obtain() 而非 new Message()。
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
private static void handleCallback(Message message) {
message.callback.run();
}
post 系列內部同樣調用 send,只是先把 Runnable 塞進 Message 的 callback 字段。分發時走 handleCallback 分支,直接調用 run()——注意這並不會創建新線程,而是在當前(即 Looper 所屬)線程中同步執行。
post 與 send 的區別:post 發送的是自帶處理邏輯(Runnable)的消息,在 handleCallback 中執行;send 發送的是裸消息,只能在 handleMessage 中處理。
Web開發基礎:Tomcat配置與HTTP協議詳解
Web開發概述 Web開發通常可以分為靜態資源與動態資源兩大類。靜態資源的內容固定不變,例如HTML、CSS與JavaScript;動態資源則會依據請求參數、使用者狀態或
Android VideoView 全屏播放問題解析:onMeasure 與顯示比例
原生 VideoView 在部分場景下無法完全填滿螢幕,原因在於其 onMeasure 會依影片比例調整寬高。當狀態欄與導覽欄透明時,可用區域變化會影響最終顯示尺寸。若希
用 Android Studio 一鍵把專案分享到 GitHub 的完整教學
把 Android Studio 裡的專案上傳到 GitHub,其實沒有想像中複雜。只要善用 IDE 內建的版本控制功能,幾個步驟就能完成初始化、提交與推送。以下就帶你走
Layout_weight 面試常見問題解析
layout_weight 是 Android 版面設計中很常見的屬性,尤其在 LinearLayout 中用來分配剩餘空間。面試時常會考驗候選人是否理解它的計算方式,以