編輯:關於 Android 程式設計
Looper 類(system/core/libutils/Looper.cpp)提供了 pollOnce() 與 wake() 兩個函數,用來完成「睡眠等待」與「喚醒」。搜索 pollOnce() 可以看到它在系統中有大量使用:
InputDispatcher::dispatchOnce() [InputDispatcher.cpp] MessageQueue::waitMessage() [frameworks/native/services/surfaceflinger/MessageQueue.cpp] SensorService::SensorEventAckReceiver::threadLoop() [frameworks/native/services/sensorservice/SensorService.cpp]
InputDispatcher 對 Looper 的用法很好理解:在沒有按鍵或觸摸等輸入事件時,線程最好進入睡眠以減少開銷;一旦有輸入,這個線程需要立刻被喚醒,把按鍵消息傳給 WMS。
// 進入睡眠等待 InputDispatcher::dispatchOnce() -> mLooper->pollOnce(timeoutMillis) // 被喚醒 InputDispatcher::notifyKey() -> mLooper->wake() // notifyKey() 的調用路徑 InputReader::loopOnce() -> InputReader::processEventsLocked() -> InputReader::processEventsForDeviceLocked() -> KeyboardInputMapper::process() // 按鍵 -> KeyboardInputMapper::processKey() -> getListener()->notifyKey()
那 Looper 自己又是怎麼實現睡眠與喚醒的?答案是利用了 Linux 內核的 epoll 機制。當被監控的文件(通過 epoll_ctl 的 EPOLL_CTL_ADD 加入)發生 I/O 時,epoll_wait 就會從睡眠中醒來,此時可以檢查是哪個(或哪些)文件描述符可以讀寫,從而做進一步處理。(Input Framework 中的 EventHub 同樣用 epoll 來檢查 /dev/input 下的輸入設備。)
從 Looper 的構造函數可以看到,它先創建了一對 pipe,再初始化 epoll fd 並把管道讀端監聽起來:
Looper::Looper(bool allowNonCallbacks)
: mAllowNonCallbacks(allowNonCallbacks),
mSendingMessage(false),
mResponseIndex(0),
mNextMessageUptime(LLONG_MAX) {
int wakeFds[2];
int result = pipe(wakeFds); // 創建管道
mWakeReadPipeFd = wakeFds[0]; // 讀端
mWakeWritePipeFd = wakeFds[1]; // 寫端
fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
mIdling = false;
mEpollFd = epoll_create(EPOLL_SIZE_HINT);
struct epoll_event eventItem;
memset(& eventItem, 0, sizeof(epoll_event));
eventItem.events = EPOLLIN; // 監聽讀事件
eventItem.data.fd = mWakeReadPipeFd; // 指定被監聽的 fd
epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, & eventItem);
}
而 pollInner() 中真正阻塞等待的就是 epoll_wait():
int Looper::pollInner(int timeoutMillis) {
int result = POLL_WAKE;
mResponses.clear();
mResponseIndex = 0;
mIdling = true;
struct epoll_event eventItems[EPOLL_MAX_EVENTS];
// 阻塞等待,直到有事件發生或超時
int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
for (int i = 0; i < eventCount; i++) {
int fd = eventItems[i].data.fd;
uint32_t epollEvents = eventItems[i].events;
if (fd == mWakeReadPipeFd) {
if (epollEvents & EPOLLIN) {
awoken(); // 讀事件:把管道裡的數據讀乾淨
} else {
// 其他情況處理
}
} else {
// 處理普通 fd 上的請求
}
}
return result;
}
對應地,wake() 就是往管道寫端寫入一個字符,從而把 epoll_wait 喚醒:
void Looper::wake() {
ssize_t nWrite;
do {
nWrite = write(mWakeWritePipeFd, "W", 1);
} while (nWrite == -1 && errno == EINTR);
if (nWrite != 1) {
if (errno != EAGAIN) {
ALOGW("Could not write wake signal, errno=%d", errno);
}
}
}
Java 層 android.os.MessageQueue 的 next() 在取下一條消息時,若隊列為空就會調用 nativePollOnce(),最終走到 C++ 層 Looper 的 pollOnce(),進入睡眠等待。
static void android_os_MessageQueue_nativePollOnce(JNIEnv* env, jclass clazz,
jlong ptr, jint timeoutMillis) {
NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
nativeMessageQueue->pollOnce(env, timeoutMillis);
}
void NativeMessageQueue::pollOnce(JNIEnv* env, int timeoutMillis) {
mInCallback = true;
mLooper->pollOnce(timeoutMillis); // 即 Looper.cpp 中的 pollOnce()
mInCallback = false;
if (mExceptionObj) {
env->Throw(mExceptionObj);
env->DeleteLocalRef(mExceptionObj);
mExceptionObj = NULL;
}
}
同樣地,enqueueMessage 在寫完消息之後,也會通過 JNI 調用 Looper 的 wake 函數把睡眠中的線程喚醒。這就構成了「有消息就喚醒,沒消息就睡眠」的完整閉環。
Android 的消息處理機制有三個核心類:Looper、Handler 和 Message。其實還有一個 MessageQueue(消息隊列),但它被封裝在 Looper 內部,我們通常不直接與它打交道,因此不把它算作核心類。
Looper 字面意思是「循環者」,它被設計用來把一個普通線程變成 Looper 線程——所謂 Looper 線程,就是循環工作的線程。在開發中(尤其是 GUI 開發)我們經常需要這樣的線程:不斷循環,一旦有新任務就執行,執行完繼續等待下一個任務。
public class LooperThread extends Thread {
@Override
public void run() {
// 將當前線程初始化為 Looper 線程
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// 在這裡處理收到的消息
}
};
// 開始循環處理消息隊列
Looper.loop();
}
}
就這麼兩行核心代碼,線程就「升級」成了 Looper 線程。下面放慢鏡頭看看它們各自做了什麼。

執行完之後,你的線程中就擁有一個 Looper 對象,它內部維護著一個消息隊列 MQ。注意,一個線程只能有一個 Looper 對象,原因看源碼:
public class Looper {
// 每個線程中的 Looper 其實是一個 ThreadLocal,即線程本地存儲(TLS)
private static final ThreadLocal sThreadLocal = new ThreadLocal();
final MessageQueue mQueue; // Looper 內部的消息隊列
Thread mThread; // 所屬線程
private Looper() {
mQueue = new MessageQueue();
mThread = Thread.currentThread();
}
/** 在調用線程的 TLS 中創建 Looper 對象 */
public static final void prepare() {
if (sThreadLocal.get() != null) {
// 已有 Looper 的線程再次調用會直接拋異常
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper());
}
}
源碼一目了然:prepare() 的核心就是把 Looper 對象存進 ThreadLocal,而 ThreadLocal 天然保證每個線程一份,這也就解釋了「一線程一 Looper」的由來。

調用 loop() 之後,Looper 線程才真正開始工作:它不斷從自己的消息隊列中取出隊頭消息並執行。
public static final void loop() {
Looper me = myLooper(); // 拿到當前線程的 Looper
MessageQueue queue = me.mQueue; // 拿到它的消息隊列
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
while (true) {
Message msg = queue.next(); // 取出下一條消息(隊列空時在這裡阻塞)
if (msg == null) {
return;
}
if (msg.target == null) {
// target 為 null 是結束信號,退出循環
return;
}
if (me.mLogging != null) {
me.mLogging.println(">>>>> Dispatching to " + msg.target + " "
+ msg.callback + ": " + msg.what);
}
// 關鍵:把真正的處理工作交給 message 的 target,也就是 Handler
msg.target.dispatchMessage(msg);
if (me.mLogging != null) {
me.mLogging.println("<<<<< Finished to " + msg.target + " "
+ msg.callback);
}
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf("Looper", "Thread identity changed while dispatching to "
+ msg.target.getClass().getName());
}
msg.recycle(); // 回收復用
}
}
除了 prepare() 和 loop(),Looper 還提供了幾個實用方法:
// 取得當前線程的 Looper(任意線程調用都返回該線程的 Looper)
public static final Looper myLooper() {
return (Looper) sThreadLocal.get();
}
// 取得 Looper 所屬的線程
public Thread getThread() {
return mThread;
}
// 結束 Looper 循環:本質是往隊列裡放一條 target 為 null 的消息
public void quit() {
Message msg = Message.obtain();
mQueue.enqueueMessage(msg, 0);
}
小結三點:
那消息是怎麼被放到 MQ 上的?這就是 Handler 的職責。Handler 扮演了「投遞消息」與「處理消息」兩個角色(它只處理由自己發出的消息):通知 MQ 它有一個任務要執行(sendMessage),等 loop 到這條消息時再執行該任務(handleMessage),整個過程是異步的。
Handler 創建時會關聯一個 Looper,默認構造方法關聯的是當前線程的 Looper:
public class Handler {
final MessageQueue mQueue; // 關聯的消息隊列
final Looper mLooper; // 關聯的 Looper
final Callback mCallback;
public Handler() {
// 默認關聯當前線程的 Looper
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
// 直接複用關聯 Looper 的 MQ,因此它的消息都會投到這個隊列上
mQueue = mLooper.mQueue;
mCallback = null;
}
}
給之前的 LooperThread 加上 Handler:
public class LooperThread extends Thread {
private Handler handler1;
private Handler handler2;
@Override
public void run() {
Looper.prepare();
handler1 = new Handler();
handler2 = new Handler();
Looper.loop();
}
}
效果如下圖。可以看到,一個線程可以有多個 Handler,但只能有一個 Looper。

有了 Handler,我們就可以用 post(Runnable)、postAtTime()、postDelayed()、sendEmptyMessage()、sendMessage()、sendMessageAtTime()、sendMessageDelayed() 這些方法往 MQ 投遞消息了。
光看 API 會覺得 Handler 能發兩種消息:Runnable 和 Message。但實際上 post 發出的 Runnable 最終都會被封裝成 Message:
/** 向關聯的 MQ 投遞 Runnable,其 run() 將在 Handler 所屬的 Looper 線程中執行 */
public final boolean post(Runnable r) {
return sendMessageDelayed(getPostMessage(r), 0);
}
private final Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r; // 把 Runnable 設為 Message 的 callback
return m;
}
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
boolean sent = false;
MessageQueue queue = mQueue;
if (queue != null) {
msg.target = this; // 必須把 target 設為自己
sent = queue.enqueueMessage(msg, uptimeMillis);
} else {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
}
return sent;
}
歸納一下,通過 Handler 發出的 Message 有兩個特點:
消息處理由核心方法 dispatchMessage(Message) 與鉤子方法 handleMessage(Message) 共同完成:
/** 由 Looper 調用 */
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
// 消息帶了 callback(即 Runnable 消息),優先執行它
handleCallback(msg);
} else {
// Handler 自身設了 Callback 的話先交給它
if (mCallback != null) {
// 這種方式允許 Activity 直接實現 Handler.Callback 接口,
// 避免自己寫 Handler 子類
if (mCallback.handleMessage(msg)) {
return;
}
}
// 都沒有,則走子類重寫的鉤子方法
handleMessage(msg);
}
}
private final void handleCallback(Message message) {
message.callback.run(); // 直接調用 run()
}
/** 由子類實現的鉤子方法 */
public void handleMessage(Message msg) { }
可見除了 handleMessage() 和 Runnable 的 run() 需要開發者實現具體邏輯之外,Handler 的內部工作機制對我們是完全透明的——這正是 Handler API 設計的精妙之處。
Handler 之所以強大,歸功於兩個特性:


這就完美解決了 Android 最經典的痛點——不能在工作線程中更新 UI。Android 的主線程本身也是一個 Looper 線程(Looper 在系統中應用極廣),我們在主線程中創建的 Handler 默認關聯主線程的 MQ。因此最典型的用法就是:在 Activity 中創建 Handler 並把引用傳給工作線程,工作線程完成任務後通過 Handler 發送消息,通知 Activity 更新界面。

public class TestDriverActivity extends Activity {
private TextView textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textview = (TextView) findViewById(R.id.textview);
// 創建並啟動工作線程
Thread workerThread = new Thread(new SampleTask(new MyHandler()));
workerThread.start();
}
public void appendText(String msg) {
textview.setText(textview.getText() + "\n" + msg);
}
class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
String result = msg.getData().getString("message");
appendText(result); // 在主線程更新 UI
}
}
}
public class SampleTask implements Runnable {
private static final String TAG = SampleTask.class.getSimpleName();
private Handler handler;
public SampleTask(Handler handler) {
this.handler = handler;
}
@Override
public void run() {
try {
Thread.sleep(5000); // 模擬耗時任務,如下載
handler.sendMessage(prepareMessage("task completed!"));
} catch (InterruptedException e) {
Log.d(TAG, "interrupted!");
}
}
private Message prepareMessage(String str) {
Message result = handler.obtainMessage();
Bundle data = new Bundle();
data.putString("message", str);
result.setData(data);
return result;
}
}
除此之外,由於 Handler 能 post Runnable,它還可以與 Looper 配合實現經典的 Pipeline(流水線線程)模式,讓多個線程串成一條數據加工鏈。
在整個消息處理機制中,Message 又被稱為 task,它封裝了任務攜帶的信息以及處理該任務的 Handler。使用上有幾點值得注意:
把 Android 模組打成 jar 並用 ProGuard 混淆的實操筆記
又是一個睡不著的夜裡,來處理一件拖了很久的事:專案裡有部分程式碼想對外提供成 jar,而且不希望被人直接反編譯看光光。 步驟一:打包 jar 在 Eclipse 中
Android TextView 控制項的兩種用法:XML 靜態設定與程式碼動態綁定
本文說明 TextView 的兩種常見用法。往後大多數章節也一樣,我們會逐個拆解常用控制項——因為把這些控制項組合起來,就是一個完整的應用。 先觀察一件事 如果你留意一
Android AutoCompleteTextView 實現搜索歷史記錄
AutoCompleteTextView 常用於搜尋框,能在使用者輸入時顯示提示。若把提示來源改為歷史紀錄,就能讓搜尋體驗更貼近實際需求。 以 SharedPrefere
SlidingMenu 實作側滑欄完整教學:環境整合、屬性配置與常見錯誤排除
先感謝各位國內外先進無私的分享。 近期專案需要一個側滑欄,翻了些資料後發現用 SlidingMenu 實作相對省事,這裡整理成筆記,之後需要時可以直接回頭查。 一、準備