編輯:關於 Android 程式設計
說到訊息機制,我們一定會想到 Handler。由於 Android 系統規定主執行緒不能阻塞超過 5 秒,否則會出現「Application Not Responding」(ANR)。也就是說,你不能在主執行緒中進行耗時操作(網路請求、資料庫操作等),只能放到子執行緒。那麼,如果在子執行緒中直接存取 UI 會發生什麼事呢?
public void click(View v){
new Thread(new Runnable() {
@Override
public void run() {
mTextView.setText("2");
}
}).start();
}
結果不出所料地報錯了:
在 ViewRootImpl 的 checkThread() 中會檢查是否為主執行緒,若不是則拋出異常。

那麼,該如何才能在子執行緒中順利更新 UI 呢?答案就是 Handler 機制!
先來看看如何改進程式碼,接著再詳細分析 Handler 的運作原理。子執行緒中透過 Handler 發送訊息:
public void click(View v){
new Thread(new Runnable() {
@Override
public void run() {
Message msg = mHandler.obtainMessage();
msg.arg1 = 2;
mHandler.sendMessage(msg);
}
}).start();
}
然後在 handleMessage 中更新 UI:
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
mTextView.setText(msg.arg1+"");
}
};
這樣就成功了。僅僅知道怎麼用顯然不夠,我們還得弄清楚背後到底做了什麼。
當我們呼叫 sendMessage 時,最終其實呼叫的是 sendMessageAtTime(msg, uptimeMillis),其源碼如下:
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
它會呼叫 enqueueMessage() 把 Message 送進 MessageQueue。那 MessageQueue 是什麼呢?顧名思義就是訊息佇列。當我們建立 Handler 時,它需要與 Looper 關聯,而 Looper 類有一個成員變數 MessageQueue mQueue,它就是訊息佇列,用來接收 Handler 發送的 Message。MessageQueue 內部並不是用陣列儲存,而是採用鏈結串列的資料結構,方便新增與刪除。
來看看 Looper.loop() 源碼,這個方法就是負責把 Message 交給 Handler.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;
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
return; // 佇列正在結束
}
msg.target.dispatchMessage(msg);
msg.recycleUnchecked();
}
}
第 3、4 行:判斷 Looper 物件是否為空,若為空則拋出「No Looper; Looper.prepare() wasn't called on this thread.」異常。換句話說,如果我們在子執行緒中建立 Handler 並呼叫 sendMessage(),由於沒有 Looper 物件,就會拋出此異常。我們可以透過 Looper.prepare() 把當前執行緒轉為 Looper 執行緒。
主要看 for (;;) 那段程式碼,它是個無窮迴圈,不斷執行 next() 方法,若有新訊息,就交給 msg.target.dispatchMessage(msg)。這裡的 msg.target 其實就是 Handler 物件。
那麼 Handler.dispatchMessage(msg) 到底做了什麼呢?
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
看到這裡就明白了,它最終呼叫的就是 handleMessage(),所以我們就能輕鬆更新 UI 了!那麼 mCallback.handleMessage(msg) 又是什麼呢?看下面這段程式碼:
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
Toast.makeText(getApplicationContext(),"1",Toast.LENGTH_SHORT).show();
return false;
}
){
@Override
public void handleMessage(Message msg) {
Toast.makeText(getApplicationContext(),"2",Toast.LENGTH_SHORT).show();
}
};
注意:在第 5 行我 return false,結果吐司先顯示 1,顯示完之後再顯示 2。當 return true 時,結果吐司只顯示 1。由此可見,這其實是用來攔截處理訊息的機制 —— 回傳 true 就攔截下來,不再往下走 handleMessage。
剛才提到 Looper.prepare() 可以把當前執行緒轉為 Looper 執行緒,來看看它的源碼:
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。而一個 Looper 內部維護著 MessageQueue,當有訊息時,Looper 從 MessageQueue 中取出訊息交給 Handler 處理,這樣它們之間就建立起關係了。
源碼中的 sThreadLocal.set(new Looper(quitAllowed)) 運用了 ThreadLocal,它保證每個執行緒都有自己獨立的 Looper 實例。要讓 Looper 不斷從 MessageQueue 取訊息,就必須呼叫 Looper.loop()。
在子執行緒中發送訊息的完整程式碼如下:
public void click(View v){
final Handler handler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
handler.sendMessage(...);
Looper.loop();
}
}).start();
}
注意 Looper.prepare() 與 handler.sendMessage() 這兩個方法的順序不能顛倒,我們來看 Handler 的建構方法:
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;
}
注意這段程式碼 mLooper = Looper.myLooper(),若為空就拋出異常,意思就是必須先呼叫 Looper.prepare()。這就是為什麼順序不能改變!
那麼讀者可能會問:我們在主執行緒建立 Handler 物件,並沒有呼叫 Looper.prepare() 也沒出問題,這是為什麼呢?的確如此,因為 ActivityThread 的 main() 函式中,Looper.prepareMainLooper() 已經自動幫我們建立好 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();
}
}
其中 sMainLooper = myLooper(),而 myLooper() 就是回傳 sThreadLocal.get(),也就是當前執行緒的 Looper。
講了這麼多,來看一張經典的關係圖,幫助理解 Handler、MessageQueue、Looper 之間的關係:

用一個生活化的比喻:老闆正在和員工開會,員工想上廁所,出於禮貌對老闆說「我要去上廁所」(sendMessage 到 MessageQueue 中);老闆思考了一會兒,回覆「你去吧」(Looper.loop());最後員工去上廁所了(handleMessage)。從詢問到最終上廁所,整個過程都是員工在做,這就是它們之間的關係。
其實 Handler 發送訊息有多種方式,例如 msg.sendToTarget()、sendMessageAtFrontOfQueue()、sendEmptyMessage()、sendEmptyMessageDelayed()、post()、postDelayed() 等。雖然方法眾多,但本質上都是透過 Handler.handleMessage() 來實作的。有興趣的讀者可以進一步查閱 Android 官方文件。
ListView 多類型項目的實作方式
在實際開發中,ListView 常需要顯示多種不同樣式的項目,例如字母標題與一般內容列。要實作這類效果,除了基本 Adapter 外,還需要覆寫項目類型相關方法。 基本
Android 布局动画详解:从 animateLayoutChanges 到 LayoutTransition
所谓布局动画,是围绕 ViewGroup 展开的概念,指的是当 ViewGroup 增删子 View 时,这些子 View 所呈现的过渡动画效果。Android 官方文档
Android 學習筆記:Sdcard 存儲方法及操作工具類封裝
一、專案目錄結構二、核心程式碼FileService.java 是操作 sdcard 的工具類,涵蓋了寫入根目錄、寫入自訂目錄、讀取資料、依副檔名分類保存以及刪除檔案等功
Android 自定義 View 打造彈性小球動畫(貝茲曲線篇)
先看成果 這次要實作的是一個會左右移動、並且不斷被「拉長壓扁」的彈性小球。看起來複雜,實際上核心只有一個觀念:用 Path.cubicTo() 畫出封閉的圓形,再依小球