編輯:關於 Android 程式設計
在一次面試中,技術面試官問到了 Handler 的消息機制。細細回想,日常開發中最常見的用法,就是在主線程(Activity)建立一個 Handler 物件,另開一個 Thread 非同步載入資料,載入完成後再把結果 send 回主線程的 Handler,由它來處理並更新界面。本文就從這個熟悉的場景出發,深入剖析其底層原理。
public class HandlerTestActivity extends Activity {
private TextView tv;
private static final int UPDATE = 0;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// 接收消息並更新 UI 線程上的控制項
if (msg.what == UPDATE) {
tv.setText(String.valueOf(msg.obj));
}
super.handleMessage(msg);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.tv);
new Thread() {
@Override
public void run() {
try {
for (int i = 0; i < 100; i++) {
Thread.sleep(500);
Message msg = new Message();
msg.what = UPDATE;
msg.obj = "更新後的值:" + i;
handler.sendMessage(msg);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
}
每個 Thread 都對應一個 Looper,這個 Looper 類用於管理其中的消息隊列(MessageQueue)。而 Handler 的作用,則是把消息傳遞到這個隊列中,並在 Looper 取出消息後交給對應的 Handler 處理。
Looper 是與線程綁定的。若想在子線程中取得一個 Looper,需要這樣做:
Looper.prepare(); Looper looper = Looper.myLooper();
// 準備 Looper 相關事宜
public static void prepare() {
// 每個線程只能有一個 Looper 物件
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper());
}
// 構造函數:新建消息隊列,並記錄當前線程
private Looper() {
mQueue = new MessageQueue();
mRun = true;
mThread = Thread.currentThread();
}
// 從當前線程的 ThreadLocal 中取出設置的 Looper
public static final Looper myLooper() {
return (Looper) sThreadLocal.get();
}
// 運行消息隊列,需搭配 quit() 才能結束循環
public static void loop() {
Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
MessageQueue queue = me.mQueue;
while (true) {
Message msg = queue.next(); // 可能阻塞
if (msg != null) {
if (msg.target == null) {
// target 為空是退出消息的標識
return;
}
msg.target.dispatchMessage(msg);
msg.recycle();
}
}
}
public Handler() {
// 先取得一個 Looper 物件;若在子線程,需先 prepare()
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 = null;
}
// 從全域消息池取得一個 Message,比 new 更有效率
public final Message obtainMessage() {
return Message.obtain(this);
}
new Thread() {
public void run() {
Looper.prepare();
Handler h = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg != null) {
String strMsg = (String) msg.obj;
System.out.println(strMsg);
}
}
};
Message msg = h.obtainMessage();
msg.obj = "add";
msg.sendToTarget();
Looper.loop(); // 進入循環,查看消息隊列
}
}.start();
1. 子線程也可以有 Handler。Handler 本質上只是從當前線程取得 Looper,用以監聽與操作 MessageQueue。
2. 子線程必須先呼叫 prepare() 才能取得 Looper。因為子線程只是一個普通線程,其 ThreadLocal 中並未設置過 Looper,若直接建立 Handler 便會抛出異常;而 Looper 的 prepare() 方法中的 sThreadLocal.set(new Looper()) 正是完成 Looper 設置的關鍵。
Android 實現 ViewPager 花屏(翻頁)效果的基本用法
本篇示範如何用 ViewPager 實作類似「花屏」的多頁滑動切換效果,並搭配 PagerTitleStrip 顯示每一頁的標題。 1. 運行效果圖 2. 程式碼實現
Android 開發學習筆記(四):深入認識 Activity
4.1 Activity 是什麼Activity 可以說是整個應用程式的入口,負責創建視窗(透過 setContentView(View))並與使用者互動。理解 Acti
Android 變色狀態欄實作:透明狀態欄、Toolbar 與 SystemBarTint
透明、變色與沉浸式狀態欄的差別 在 Android 中,常見說法包含沉浸式狀態欄、透明狀態欄與變色狀態欄。三者常被混用,但概念不同。 沉浸式模式會讓狀態欄與虛擬鍵隱藏,需
Android 4.4 Framework 剖析:Zygote 進程的啟動全流程
Android 開機過程中的第一個進程是 init,它會接著拉起兩個關鍵的系統服務進程:ServiceManager 與 Zygote。本文聚焦在後者。 Zygote 俗