編輯:關於 Android 程式設計
作者:羅朝輝(https://blog.csdn.net/kesalin),CC 授權,轉載請註明出處。
前文〈Android 多執行緒分析之二:Thread 的實現〉已詳細分析了 Android Thread 如何建立、執行與銷毀,重點在對應的 native 方法。本篇聚焦於 Framework 層的多執行緒類別:Handler、Looper、MessageQueue、Message,以及它們與 Thread 的關係。
可以用一個不太嚴謹但很形象的比喻來理解它們的關聯:如果把 Thread 比作生產車間,那麼 Looper 就是這車間裡的生產線,這條生產線源源不斷地從 MessageQueue 中取得材料 Message,並分派處理 Message(由於 Message 通常是完備的,所以 Looper 多數情況下只是調度,讓 Message 的 Handler 去處理它)。
正因為訊息要在 Looper 中處理,而 Looper 又必須運行在 Thread 中,所以我們不能隨隨便便在非 UI 執行緒裡操作 UI。UI 操作通常透過投遞訊息來實現,只有往正確的 Looper 投遞才能被處理——而對 UI 來說,這個 Looper 一定運行在 UI 執行緒中。
寫 App 時我們常這樣使用 Handler:
Handler mHandler = new Handler();
mHandler.post(new Runnable() {
@Override
public void run() {
// do some work
}
});
或者覆寫 handleMessage:
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.i("UI thread", " >> handleMessage()");
switch (msg.what) {
case MSG_LOAD_SUCCESS:
Bitmap bitmap = (Bitmap) msg.obj;
mImageView.setImageBitmap(bitmap);
mProgressBar.setProgress(100);
mProgressBar.setMessage("Image downloading success!");
mProgressBar.dismiss();
break;
case MSG_LOAD_FAILURE:
mProgressBar.setMessage("Image downloading failure!");
mProgressBar.dismiss();
break;
}
}
};
Message msg = mHandler.obtainMessage(MSG_LOAD_FAILURE, null);
mHandler.sendMessage(msg);
那麼在 post/sendMessage 背後到底發生了什麼?下面從 Handler 的建構子開始拆。
final MessageQueue mQueue;
final Looper mLooper;
final Callback mCallback;
final boolean mAsynchronous;
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
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 Handler() {
this(null, false);
}
mLooper:執行緒的訊息處理迴圈。注意並非每個執行緒都有 Looper,因此 Framework 中的執行緒可分為兩類:有 Looper 的與無 Looper 的。為方便開發,Framework 另外提供了一個自帶 Looper 的 Thread 實作——HandlerThread。
/**
* 一個自帶 looper 的 Thread。
* 建立 looper 之後即可用來建立 Handler。
* 注意:start() 仍必須呼叫。
*/
public class HandlerThread extends Thread {
Looper mLooper;
/** 可在 Looper 迴圈前執行的額外初始化 */
protected void onLooperPrepared() { }
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
public Looper getLooper() {
if (!isAlive()) return null;
// 若已啟動,等待 looper 建立完成
synchronized (this) {
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) { }
}
}
return mLooper;
}
}
HandlerThread 與 Thread 相比,多了一個 Looper 型別的成員 mLooper,它在 run() 中由 Looper.prepare() 建立並存入 TLS:
/** 把當前執行緒初始化為一個 looper */
public static void prepare() {
prepare(true);
}
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));
}
/** 取得與當前執行緒關聯的 Looper,無關聯則回傳 null */
public static Looper myLooper() {
return sThreadLocal.get();
}
注意那句 "Only one Looper may be created per thread"——每個執行緒只能有一個 Looper,重複呼叫 prepare() 會直接拋出例外。這也是為什麼 Handler 能靠 ThreadLocal 存取 Looper,而不需要全域查表。
建立完成後,最後透過 Looper.loop() 運行訊息迴圈,不斷從 MessageQueue 取訊息、分派、回收。
成員 mQueue 就是 mLooper 的成員,這裡單獨拉出來只是為了少打一層點號。成員 mCallback 提供了另一種使用 Handler 的簡便途徑:只需實作回呼介面,不必去 subclass Handler。
/** 用來避免 subclass Handler 的回呼介面 */
public interface Callback {
public boolean handleMessage(Message msg);
}
成員 mAsynchronous 標識是否異步處理訊息;若為 true,透過該 Handler 取得的訊息都會被強制設為異步。
如同 Thread 有無 Looper 之分,Handler 的建構子也分兩大類:自帶 Looper 與 外部 Looper。若提供了 Looper,訊息就在該 Looper 中處理;否則在當前執行緒的 Looper 中處理——此時必須確保當前執行緒真的有 Looper。
所有 UI 執行緒都有 Looper,因為 View/Widget 的實作中大量使用訊息,需要 UI 執行緒提供 Looper 來處理。以 View 為例:
// View.java
public boolean post(Runnable action) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.post(action);
}
// 尚未 attach 時先排入佇列
ViewRootImpl.getRunQueue().post(action);
return true;
}
// ViewRootImpl.java
static RunQueue getRunQueue() {
RunQueue rq = sRunQueues.get();
if (rq != null) return rq;
rq = new RunQueue();
sRunQueues.set(rq);
return rq;
}
/**
* 當 View 尚未 attach 到 Handler 時,用這個佇列暫存待執行的動作,
* 並在下一次 performTraversals 時執行。
*/
static final class RunQueue {
void executeActions(Handler handler) {
synchronized (mActions) {
final ArrayList<HandlerAction> actions = mActions;
final int count = actions.size();
for (int i = 0; i < count; i++) {
final HandlerAction handlerAction = actions.get(i);
handler.postDelayed(handlerAction.action, handlerAction.delay);
}
actions.clear();
}
}
}
作為所有控制項基類的 View 提供了 post 方法,用於向 UI 執行緒發送訊息並在其 Looper 中處理。而 UI 執行緒一定有 Looper,這是由 ActivityThread 保證的:
public final class ActivityThread {
final Looper mLooper = Looper.myLooper();
}
UI 操作需要向 UI 執行緒發送訊息並在其 Looper 中處理,這就是為什麼我們不能在非 UI 執行緒更新 UI 的原因。在非 UI 執行緒建立 Handler 時,要麼因為該執行緒沒有 Looper 導致 myLooper() 回傳 null 而拋出 RuntimeException,要麼即使提供了 Looper,那也不是 UI 執行緒的 Looper,同樣無法處理控制項訊息。
為此 ViewRootImpl 提供了一個強制檢測方法:
void checkThread() {
if (mThread != Thread.currentThread()) {
throw new CalledFromWrongThreadException(
"Only the original thread that created a view hierarchy can touch its views.");
}
}
其中 mThread 在 ViewRootImpl 建構子中賦值,就是 UI 執行緒;Thread.currentThread() 是當前執行緒。兩者不符就拋出 CalledFromWrongThreadException。
若把「使用 Thread 異步下載圖像」的範例改成在 Thread 的 run() 中直接設定 ImageView,就會看到這樣的錯誤:
W/dalvikvm(796): threadid=11: thread exiting with uncaught exception (group=0x40a71930)
E/AndroidRuntime(796): FATAL EXCEPTION: Thread-75
E/AndroidRuntime(796): android.view.ViewRootImpl$CalledFromWrongThreadException:
Only the original thread that created a view hierarchy can touch its views.
E/AndroidRuntime(796): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4746)
E/AndroidRuntime(796): at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:823)
E/AndroidRuntime(796): at android.widget.ImageView.setImageBitmap(ImageView.java:421)
E/AndroidRuntime(796): at com.example.thread01.MainActivity$2$1.run(MainActivity.java:80)
/** 子類別必須實作這個方法來接收訊息 */
public void handleMessage(Message msg) { }
/** 系統訊息在這裡處理 */
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();
}
這段程式揭示了訊息處理的三級優先順序:
dispatchMessage 是在 Looper.loop() 中被呼叫,也就是運行在執行緒的訊息迴圈裡,這樣 Handler 才能持續處理各種訊息。
先理一下四者的關係:Thread 需要 Looper 才能處理訊息(也就是說 Looper 運行在 Thread 中),這透過在自訂 Thread 的 run() 中呼叫 Looper.prepare() 與 Looper.loop() 實現。接著在 loop() 中不斷從 MessageQueue 取出由 Handler 投遞的 Message,並呼叫 Message 所持有的 Handler 的 dispatchMessage 來處理。
final MessageQueue mQueue;
final Thread mThread;
volatile boolean mRun;
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mRun = true;
mThread = Thread.currentThread();
}
/** 把當前執行緒初始化為 looper,並標記為應用程式的主 looper */
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
/** 運行訊息佇列 */
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.recycle();
}
}
Looper 的建構子很簡單:建立 MessageQueue、把當前執行緒存進 mThread。但它是私有的,只能透過 prepare() 與 prepareMainLooper() 呼叫。後者傳入 false,表示主 Looper 不允許中途被終止,建立後保存在靜態變數 sMainLooper 中。
整個 Framework 只有兩處呼叫 prepareMainLooper:
1. SystemServer 的 ServerThread——絕大部分系統服務都在這條執行緒中初始化,由 init2() 啟動:
public static final void init2() {
Slog.i(TAG, "Entered the Android system server!");
Thread thr = new ServerThread();
thr.setName("android.server.ServerThread");
thr.start();
}
class ServerThread extends Thread {
@Override
public void run() {
Looper.prepareMainLooper();
// ... 建立各項系統服務
Looper.loop();
Slog.d(TAG, "System ServerThread is exiting!");
}
}
2. ActivityThread 的 main()——也就是 UI 主執行緒:
public static void main(String[] args) {
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
AsyncTask.init();
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
注意這裡的 AsyncTask.init()——AsyncTask 之所以能進行 UI 操作,正是因為它在這裡完成了初始化,取得了主執行緒的 Handler 與 Looper。而最後那句「loop 意外退出」的例外,也說明了 loop() 是永不返回的無窮迴圈,一旦返回就代表程式到了不該到的狀態。
loop() 的實作如前所述:不斷從 MessageQueue 取訊息、分派、回收。它僅僅是一條不斷循環作業的生產流水線,MessageQueue 為它提供原材料,Handler 則是投遞原材料的人。
至於 Handler 如何把訊息放進 MessageQueue、MessageQueue 又如何管理這些訊息(例如依 what/when 排序、IdleHandler 的運作、Barrier 同步屏障等),則留待後續篇章拆解。
告別 Eclipse!Android Studio 新手入門配置全攻略(一)
寫在前面 作為一個剛踏進 Android 開發大門的新手,我曾用 Eclipse 開發過兩個自我感覺還不夠成熟的商城類 App。一路折騰下來,踩了不少坑,也總結出幾個最迫
動手打造 Android 自訂星星評分控件(支援 0.1 精度)
在 Android 開發裡,評分功能幾乎是各類應用不可避免的環節。本文將帶你從零開始,一步步打造一個高效、靈活、可自訂的星星評分控件。整個思路是直接用 onDraw 繪製
Android 經典主界面框架(二):ViewPager + Fragment 實現可滑動切換的 Tab(仿網易新聞)
第二種主界面風格以網易新聞、鳳凰新聞以及新推出的新浪博客(閱讀版)為代表,核心組合是 ViewPager + Fragment:ViewPager 的適配器裡放的不是普通
Android Framework 啟動流程解析:從 Zygote 到 SystemServer
Framework 啟動的整體目標Android 開機的過程,可以視為逐步建立系統運行所需環境的過程。從核心層、init 到 Zygote,再到 SystemServer