注意: 原始內容為空。本文聚焦 Looper 類的深度剖析:主執行緒 Looper 初始化、子執行緒建立 Looper 模板、Looper.myQueue() 獲取當前訊息隊列、IdleHandler 空閒任務調度、quit()/quitSafely() 差異、以及實際應用場景 (HandlerThread、IntentService 內部原理)。
// ActivityThread.main() 簡化流程
public static void main(String[] args) {
// 1. 初始化主執行緒 Looper
Looper.prepareMainLooper(); // 內部調用 prepare(false) + 設定 sMainLooper
// 2. 初始化 ActivityThread、載入系統資源、啟動 Binder 執行緒池
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
// 3. 進入無限循環
Looper.loop(); // 永不返回,除非 crash 或 System.exit
}
Looper.getMainLooper().quit() 無效。Looper.getMainLooper() 全域可獲取。public class LooperThread extends Thread {
private Looper looper;
private Handler handler;
public LooperThread(String name) { super(name); }
@Override public void run() {
Looper.prepare(); // 為當前執行緒建立 MessageQueue
looper = Looper.myLooper(); // 獲取綁定的 Looper
// 可在這裡建立 Handler,綁定此 Looper
handler = new Handler(looper) {
@Override public void handleMessage(Message msg) { /* 處理邏輯 */ }
};
Looper.loop(); // 進入循環,阻塞執行緒
}
public Handler getHandler() { return handler; }
public Looper getLooper() { return looper; }
public void quitSafely() { looper.quitSafely(); } // API 18+
}
// 使用
LooperThread worker = new LooperThread("Worker");
worker.start();
// 稍後從任意執行緒發送任務
worker.getHandler().post(() -> { /* 在 Worker 執行緒執行 */ });
HandlerThread ht = new HandlerThread("NetworkThread", Process.THREAD_PRIORITY_BACKGROUND);
ht.start();
Handler handler = new Handler(ht.getLooper());
handler.post(() -> { /* 網路請求、DB 操作 */ });
// 結束時
ht.quitSafely(); // 或 ht.quit() 立即退出 (可能遺留訊息未處理)
// 在 Looper 執行緒中調用
MessageQueue queue = Looper.myQueue();
// 添加 IdleHandler:隊列空閒時執行
queue.addIdleHandler(() -> {
// 執行低優先級任務:預載圖片、資料庫預取、GC 提示
preloadNextPage();
return true; // true = 保留,下次空閒再執行;false = 單次執行後移除
});
// 移除 IdleHandler
queue.removeIdleHandler(idleHandler);
public class AppStartupOptimizer {
public static void scheduleIdleTasks(Context context) {
// 確保在主執行緒
if (Looper.myLooper() != Looper.getMainLooper()) {
new Handler(Looper.getMainLooper()).post(() -> scheduleIdleTasks(context));
return;
}
Looper.myQueue().addIdleHandler(() -> {
// 1. 初始化非關鍵 SDK (統計、推送、廣告)
AnalyticsSDK.init(context);
PushSDK.init(context);
// 2. 預載熱門資料
Repository.getInstance().preloadHotData();
// 3. 提示 GC (系統會決定是否執行)
Runtime.getRuntime().gc();
return false; // 僅執行一次
});
}
}
| 方法 | 行為 | 適用場景 |
|---|---|---|
quit() | 立即設置 mQuitting = true,next() 返回 null,loop() 立即結束。**隊列中剩餘訊息丟棄**。 | 緊急停止、不關心遺留任務 (如測試、強制關閉)。 |
quitSafely() (API 18+) | 設置 mQuitting = true 並 **移除所有延遲訊息**,但 **保留已到期的同步訊息** 讓其執行完畢後再退出循環。 | 正常關閉工作執行緒,確保關鍵任務完成 (如存檔、上傳日誌)。 |
public abstract class IntentService extends Service {
private HandlerThread handlerThread;
private Handler handler;
@Override public void onCreate() {
super.onCreate();
handlerThread = new HandlerThread("IntentService[" + getClass().getSimpleName() + "]");
handlerThread.start();
handler = new Handler(handlerThread.getLooper()) {
@Override public void handleMessage(Message msg) {
Intent intent = (Intent) msg.obj;
onHandleIntent(intent); // 子類實作
}
};
}
@Override public int onStartCommand(Intent intent, int flags, int startId) {
Message msg = handler.obtainMessage();
msg.obj = intent;
handler.sendMessage(msg);
return START_REDELIVER_INTENT; // 或 START_NOT_STICKY
}
@Override public void onDestroy() {
handlerThread.quitSafely();
super.onDestroy();
}
protected abstract void onHandleIntent(Intent intent);
}
MessageQueue.next() 會在隊列空時呼叫 nativePollOnce 進入 Native epoll 休眠,釋放 CPU,有新訊息或檔案描述符事件才喚醒。Handler 建構子預設使用 Looper.myLooper(),若當前執行緒未關聯 Looper 會拋出 RuntimeException。Handler 引用,呼叫 handler.sendMessage() (線程安全,內部用 MessageQueue.enqueueMessage 加鎖)。sPool 單向鏈表,obtain() 從池取出,recycle() 歸還,減少 GC 壓力。