編輯:關於 Android 程式設計
Android 是訊息驅動的,實現訊息驅動有幾個要素:訊息的表示(Message)、訊息隊列(MessageQueue)、負責循環取出訊息的 Looper,以及負責處理訊息的 Handler。本文從使用方式一路談到源碼層面的運作流程。



名詞解析:
簡單來說:當子線程想修改 Activity 中的 UI 元件時,可建立一個 Handler 向主線程發送訊息;訊息會先進入主線程的 MessageQueue 等待,由 Looper 先入先出取出,再依 what 屬性分發給對應的 Handler 處理。
主線程已由系統初始化 Looper,直接建立 Handler 即可發送與處理訊息。以下以 Timer 定時切換圖片形成幀動畫為例:

public class MainActivity extends Activity {
int imgids[] = new int[]{ R.drawable.s_1, R.drawable.s_2, R.drawable.s_3, R.drawable.s_4,
R.drawable.s_5, R.drawable.s_6, R.drawable.s_7, R.drawable.s_8 };
int imgstart = 0;
final Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 0x123) {
imgchange.setImageResource(imgids[imgstart++ % 8]);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView imgchange = (ImageView) findViewById(R.id.imgchange);
new Timer().schedule(new TimerTask() {
@Override
public void run() { myHandler.sendEmptyMessage(0x123); }
}, 0, 200);
}
}若 Handler 寫在子線程,需自行建立 Looper,流程為:呼叫 Looper.prepare() 為當前線程建立 Looper(其建構子會建立 MessageQueue)→ 建立 Handler 並覆寫 handleMessage() → 呼叫 Looper.loop() 啟動循環。以下以計算質數為例:
public class CalPrime extends Activity {
static final String UPPER_NUM = "upper";
EditText etNum;
CalThread calThread;
class CalThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 0x123) {
int upper = msg.getData().getInt(UPPER_NUM);
List nums = new ArrayList();
outer: for (int i = 2; i <= upper; i++) {
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i != 2 && i % j == 0) { continue outer; }
}
nums.add(i);
}
Toast.makeText(CalPrime.this, nums.toString(), Toast.LENGTH_LONG).show();
}
}
};
Looper.loop();
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etNum = (EditText) findViewById(R.id.etNum);
calThread = new CalThread();
calThread.start();
}
public void cal(View source) {
Message msg = new Message();
msg.what = 0x123;
Bundle bundle = new Bundle();
bundle.putInt(UPPER_NUM, Integer.parseInt(etNum.getText().toString()));
msg.setData(bundle);
calThread.mHandler.sendMessage(msg);
}
} Android 的訊息機制主要由 Handler、Looper、MessageQueue、Message 組成,Handler 的運行依賴後三者。
應用啟動時會建立主線程(ActivityThread),其 main 方法是程式入口:
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");
}prepareMainLooper 為主線程建立 Looper,loop 則開啟訊息循環。由於最後會拋出例外,可推知 loop 內必為死循環,也就是主線程的訊息循環不允許退出。Looper 的建構子如下:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}它在其中建立訊息隊列並保存當前線程。由於建構子為 private,無法手動 new,需透過 prepare 方法建立,並將 Looper 存入 ThreadLocal:
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。ThreadLocal 實現了本地變數儲存,各線程只能取得自己存放的資料。prepareMainLooper 為主線程建立 Looper 並設定不允許退出,可透過 getMainLooper 取得:
public static void prepare() { prepare(true); }
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}loop 方法則開啟訊息循環:
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; } // 隊列退出時回傳 null
msg.target.dispatchMessage(msg);
msg.recycleUnchecked();
}
}正如所料,loop 內確實存在死循環,唯一退出方式是訊息隊列回傳 null。透過 queue.next() 取得訊息後,msg.target 即發送訊息的 Handler,交由 dispatchMessage 處理,完成後回收。也可透過 quit 與 quitSafely 退出循環,其本質是呼叫訊息隊列的 quit 方法:
public void quit() { mQueue.quit(false); }
public void quitSafely() { mQueue.quit(true); }MessageQueue 即訊息隊列,內部以單鏈表實作,以提高插入與刪除效率。
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;
}可見在沒有 Looper 的線程中無法建立 Handler。因此在子線程使用 Handler 前,必須先建立 Looper 並開啟訊息循環。
梳理整個流程:主線程建立時為其建立一個 Looper,Looper 內部同時建立一個 MessageQueue;建立 Handler 時取出當前線程的 Looper,並透過它取得 MessageQueue;Handler 在子線程發送訊息,等同在該隊列中新增一筆 Message;最後由 Looper 的訊息循環取出這筆 Message 並交由 Handler 處理。
Android 自定義滾動選擇器(Picker)完整實例代碼
本文分享一個自定義滾動選擇器的完整實現,先看看效果:它的核心思路是:用一個自定義 View,把數據列表循環排列,通過手指滑動改變偏移量,再用拋物線函數計算每個選項的字號與
Android 快速接入支付寶與微信支付的完整流程
隨著行動支付的普及,越來越多 App 導入第三方支付。這裡以支付寶為例,示範一次快速整合的過程。 一、Android 快速實現支付寶支付 1、首先前往支付寶開放平台,申請
用 ViewFlipper 實現 Android 螢幕動畫切換
ViewFlipper 是一個專門用於「多子視圖輪番展示」的容器。它同一時刻只顯示一個子 View,切換時可以套用進出動畫,配上滑動手勢判斷,就能做出類似幻燈片的翻頁
Android 圖片壓縮實戰:Bitmap 的五種常見壓縮方式
在 Android 中,圖片是以 Bitmap 的形式存在於記憶體,因此 Bitmap 的佔用大小直接影響了 App 的記憶體表現。首先要理解它的計算方式: 圖片長度 ×