之前在子線程和主線程創建使用Handler不同處的源碼分析時,追了一下應用創建和使用Handler的相關源碼。發現了在線程中使用Handler,最後就會進入loop循環,子線程要手動退出,主線程是不死就不退出;同時也和另一個問題相遇了:那就是應用的主線程最後也都在loop裏沒出來【activityThread的Main方法最後執行了Looper.loop()】爲什麼不會導致應用發生ANR呢?.今天不對這具體深入;就主要對Handler的消息循環,消息發送和消息處理的流程進行分析.這塊梳理完後,對不引發ANR的問題也就可以幫助理解了
消息循環
在loop循環中,會一直等待和處理消息。我們就從Looper.java的loop()方法入手:
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the 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(); // might block
if (msg == null) {
return;
}
...
try {
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
}
....
msg.recycleUnchecked();
}
}
在loop()中,先對其中的重要的變量進行說明:
me : looper對象,在Looper.java類的prepare()方法中創建,並保存在sMainLooper中,這裏通過myLooper()方法獲取到
queue:MessageQueue對象,在Looper類構造函數裏創建的,所以Looper中就持有了messageQueue的對象。
msg: Message;
msg.target:這就是handler
loop中有個for大循環,裏面就在不斷的獲取和處理消息。在循環中,先使用MessageQueue的next()方法從MessageQueue中獲取message,如果返回的消息爲空,loop就會退出-->線程就會退出(要是在主線程中的話-->最後應用也會退出)。我這看到這裏時就很疑惑了,難道一個應用在活着的時候,他的MessageQueue就不能爲空?但是顯然應用的MessageQueue是爲有空的時候,那問題應該就出在messageQueue的next()方法裏,或許這個next()裏面有什麼特殊,導致不會返回空。
抱着問題跳轉到MessageQueue.java中看看這個next()方法裏面是怎麼樣做的:
Message next() {
final long ptr = mPtr;
...
int nextPollTimeoutMillis = 0;
for (;;) {
...
nativePollOnce(ptr, nextPollTimeoutMillis);
...
}
}
在nex()方法中也有個for循環,它裏面有個nativePollOnce()調用。我們就看看Native層的實現,接下來跳轉到Native層的android_os_MessageQueue.cpp【這是MessageQueue對應的Native文件】
static void android_os_MessageQueue_nativePollOnce(JNIEnv* env, jobject obj,
jlong ptr, jint timeoutMillis) {
NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
nativeMessageQueue->pollOnce(env, obj, timeoutMillis);
}
在android_os_MessageQueue_nativePollOnc()函數裏面,通過nativePollOnce傳進來的ptr找到NativeMessageQueue指針。然後調用其pollOnce()函數:
void NativeMessageQueue::pollOnce(JNIEnv* env, jobject pollObj, int timeoutMillis) {
...
mLooper->pollOnce(timeoutMillis);
mPollObj = NULL;
mPollEnv = NULL;
...
}
在pollOnce()函數中這個mLooper就是Looper的一個指針,在android_os_MessageQueue.h中聲明的,所以在Native層的MessageQueue持有Looper指針,【Java層是Looper中持有MessageQueue對象】接着是調用了Looper的pollOnce()方法:
我們就跳轉到Looper.cpp中看看Looper的pollOnce()是怎麼做的:
int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
int result = 0;
for (;;) {
...
result = pollInner(timeoutMillis);
}
}
在pollOnce()中的for循環中調用了pollInner();我們在跳轉到pollInner()中看看:
int Looper::pollInner(int timeoutMillis) {
...
struct epoll_event eventItems[EPOLL_MAX_EVENTS];
int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
...
if (eventCount < 0) {
if (errno == EINTR) {
goto Done;
}
ALOGW("Poll failed with an unexpected error: %s", strerror(errno));
result = POLL_ERROR;
goto Done;
}
if (eventCount == 0) {
...
result = POLL_TIMEOUT;
goto Done;
}
...
for (int i = 0; i < eventCount; i++) {
int fd = eventItems[i].data.fd;
uint32_t epollEvents = eventItems[i].events;
if (fd == mWakeEventFd) {
if (epollEvents & EPOLLIN) {
awoken();
...
}
...
return result;
}
在pollInner()中,使用epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);來檢測mEpollFd所監控的fd是否有IO事件發生,超時時間爲timeoutMillis[這也是隨我們從Java層傳下來的]:【關於epoll,我們在之前分析Android_input系統分析EventHub::getevents時也有涉及,具體使用可以參考參考】
當mEpollFd所監控的文件描述符發生了要監控的IO事件後或者監控時間超時後,線程就從epoll_wait返回了,否則線程就會在epoll_wait函數中進入睡眠狀態了。返回後如果eventCount等於0,說明等待超時。果eventCount小於0,說明有錯誤。當eventCount大於0時,說明有IO事件發生:接着我們看awoken():
void Looper::awoken() {
uint64_t counter;
TEMP_FAILURE_RETRY(read(mWakeEventFd, &counter, sizeof(uint64_t)));
}
awoken()就是將mWakeEventFd句柄中的數據讀出。他的作用就是把mWakeEventFd裏面原有的數據讀走,以便下次再寫入。
到這裏,差不多就把消息循環大致流程梳理完了。我們可以發現,當MessageQueue爲空時,也不會返回爲空,而是線程進入休眠狀態,在native層使用epoll來監聽是否有新的消息從而喚醒線程進行消息獲取,所以在沒有手動退出和沒錯誤發生的情況下loop()是一直沒有退出,從而線程,進程都不會退出。
消息發送
消息的發送不論我們使用Handler的sendMessageXXX()還是post()方法,最後都調用了sendMessageDelayed()方法;我們接下來就從Handler.java 的sendMessageDelaye()方法出發看看消息發送的流程是怎麼樣的:
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
在sendMessageDelaye()方法中右調用了sendMessageAtTime()方法,我們接着跳轉到sendMessageAtTime()方法中看看:
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
...
return enqueueMessage(queue, msg, uptimeMillis);
}
...
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
從以上代碼可以看出,最後在Handler中調用了MessageQueue中的enqueueMessage()方法:
boolean enqueueMessage(Message msg, long when) {
...
synchronized (this) {
...
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
...
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
以上就是MessageQueue.java的enqueueMessage()方法,主要工作就是
- 將消息插入到消息隊列中
- 如果線程阻塞,我們要去喚醒線程去讀取和處理消息
消息插入到MessageQueue中時有兩種情況:
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
}
①. 當時消息隊列此時消息爲空,如上代碼所示:直接將我們的消息放進去就好,說明此時messageQueue是阻塞狀態的,我們需要喚醒事件隊列;
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
②.如果當前消息隊列不爲空,那我們就要把我們要發送的消息插入帶消息隊列中去,這需要根據消息的時間來決定的我們插入到消息隊列中的位置,具體邏輯參看上梳代碼。
當消息隊列爲空此時線程就需要我們去喚醒,這裏是使用了一個Native方法nativeWake:那我們就跳轉到Native層看看是怎麼喚醒線程的,接下來我們跳轉到android_os_MessageQueue.cpp中查看一下:
static void android_os_MessageQueue_nativeWake(JNIEnv* env, jclass clazz, jlong ptr) {
NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
nativeMessageQueue->wake();
}
...
void NativeMessageQueue::wake() {
mLooper->wake();
}
...
void Looper::wake() {
...
uint64_t inc = 1;
ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd, &inc, sizeof(uint64_t)));
...
}
如上所以:這和消息循環是調用差不多,在Native層的android_os_MessageQueue中,最終是調用了Looper的wake(),在wake()中向mWakeEventFd寫入數據,這個數據具體是什麼不重要,主要當有數據寫入;另一邊的epoll_wait()就可以檢測到有新的IO事件發生,從而喚醒線程來獲取和處理消息。
消息處理
那接下來,消息隊列理裏有消息了,我們就需要幾及時去處理消息;我們繼續回到Looper.java中的loop()方法中,看到有下面這段代碼:
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
return;
}
...
try {
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
}
在for循環中不斷地獲取消息隊列中的消息,【之前說過,當沒有消息時,線程就會阻塞,所以這裏的msg正常情況是不爲空的】
這裏是調用msg.target 的dispatchMessage()方法去處理消息;【之前說過,msg.target其實就是handler】.接下里我們看看Handler.java中是怎麼處理的:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
...
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}
如上所示:如果msg 的callback不爲空,就執行handleCallback()方法,否則如果mCallback不爲空,就執行mCallbackd的handleMessage()方法;否則執行handleMessage()方法,一般情況是默認執行handleMessage()方法來處理消息.所以Handler 的子類必須要實現ahndleMessage()方法。對接收到的消息進行處理。