編輯:關於 Android 開發
Android 是消息驅動的,實現消息驅動需要幾個要素:
平時我們最常使用的就是 Message 與 Handler;如果用過 HandlerThread 或自己實現類似 HandlerThread 的東西,可能還會接觸到 Looper;而 MessageQueue 是 Looper 內部使用的,對於標準 SDK 而言,我們無法直接實例化並使用它(其構造函數是包可見性)。
我們平時接觸到的 Looper、Message、Handler 都是用 Java 實現的。Android 作為基於 Linux 的系統,底層用 C、C++ 實現,再加上 NDK 的存在,消息驅動模型自然不會只存在於 Java 層——實際上在 Native 層也存在與 Java 層對應的類,如 Looper、MessageQueue 等。
先看一個線程想實現消息循環應該怎麼做,以 HandlerThread 為例:
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
關鍵就是標紅的兩句:先調用 prepare 初始化 MessageQueue 與 Looper,然後調用 loop 進入消息循環。先看 Looper.prepare:
public static void prepare() {
prepare(true);
}
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));
}
重載函數中 quitAllowed 默認為 true,從名字可以看出就是消息循環是否可以退出,默認可退出。而主線程(UI 線程)初始化消息循環時會調用 prepareMainLooper,傳入的是 false。這裡使用了 ThreadLocal,保證每個線程只能初始化一個 Looper。
再看 Looper 初始化時做了什麼:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mRun = true;
mThread = Thread.currentThread();
}
MessageQueue(boolean quitAllowed) {
mQuitAllowed = quitAllowed;
nativeInit();
}
Looper 初始化時新建了一個 MessageQueue 對象保存在成員 mQueue 中。MessageQueue 的構造函數是包可見性,所以我們無法直接使用。MessageQueue 初始化時調用了 nativeInit,這是一個 Native 方法:
static void android_os_MessageQueue_nativeInit(JNIEnv* env, jobject obj) {
NativeMessageQueue* nativeMessageQueue = new NativeMessageQueue();
if (!nativeMessageQueue) {
jniThrowRuntimeException(env, "Unable to allocate native queue");
return;
}
nativeMessageQueue->incStrong(env);
android_os_MessageQueue_setNativeMessageQueue(env, obj, nativeMessageQueue);
}
static void android_os_MessageQueue_setNativeMessageQueue(JNIEnv* env, jobject messageQueueObj, NativeMessageQueue* nativeMessageQueue) {
env->SetIntField(messageQueueObj, gMessageQueueClassInfo.mPtr, reinterpret_cast<jint>(nativeMessageQueue));
}
在 nativeInit 中 new 了一個 Native 層的 MessageQueue 對象,並把它的地址保存在了 Java 層 MessageQueue 的成員 mPtr 中。Android 中有很多這樣的實現:一個類在 Java 層與 Native 層都有實現,通過 JNI 的 GetFieldID 與 SetIntField 把 Native 層類實例的地址保存到 Java 層類實例的 mPtr 成員中,比如 Parcel。
再看 NativeMessageQueue 的實現:
NativeMessageQueue::NativeMessageQueue() : mInCallback(false), mExceptionObj(NULL) {
mLooper = Looper::getForThread();
if (mLooper == NULL) {
mLooper = new Looper(false);
Looper::setForThread(mLooper);
}
}
在 NativeMessageQueue 的構造函數中獲得了一個 Native 層的 Looper 對象,Native 層的 Looper 同樣使用了線程本地存儲,注意 new Looper 時傳入了參數 false。
Looper::Looper(bool allowNonCallbacks) : mAllowNonCallbacks(allowNonCallbacks), mSendingMessage(false), mResponseIndex(0), mNextMessageUptime(LLONG_MAX) {
int wakeFds[2];
int result = pipe(wakeFds);
LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
mWakeReadPipeFd = wakeFds[0];
mWakeWritePipeFd = wakeFds[1];
result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d", errno);
result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d", errno);
// Allocate the epoll instance and register the wake pipe.
mEpollFd = epoll_create(EPOLL_SIZE_HINT);
LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance. errno=%d", errno);
struct epoll_event eventItem;
memset(& eventItem, 0, sizeof(epoll_event));
eventItem.events = EPOLLIN;
eventItem.data.fd = mWakeReadPipeFd;
result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, & eventItem);
LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d", errno);
}
Native 層的 Looper 使用了 epoll。它初始化了一個管道,用 mWakeWritePipeFd 與 mWakeReadPipeFd 分別保存管道的寫端與讀端,並監聽了讀端的 EPOLLIN 事件。注意初始化列表中 mAllowNonCallbacks 的值為 false。
那 mAllowNonCallback 是做什麼用的呢?使用 epoll 僅僅是為了監聽 mWakeReadPipeFd 的事件嗎?其實 Native Looper 不僅能監聽這一個描述符,Looper 還提供了 addFd 方法:
int addFd(int fd, int ident, int events, ALooper_callbackFunc callback, void* data); int addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data);
fd 表示要監聽的描述符;ident 表示要監聽事件的標識,值必須 >=0 或為 ALOOPER_POLL_CALLBACK(-2);events 表示要監聽的事件;callback 是事件發生時的回調函數。mAllowNonCallbacks 的作用就在於此:當它為 true 時允許 callback 為 NULL,此時 ident 作為結果返回;否則不允許 callback 為空,當 callback 不為 NULL 時 ident 的值會被忽略。直接看代碼更好理解:
int Looper::addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data) {
if (!callback.get()) {
if (! mAllowNonCallbacks) {
ALOGE("Invalid attempt to set NULL callback but not allowed for this looper.");
return -1;
}
if (ident < 0) {
ALOGE("Invalid attempt to set NULL callback with ident < 0.");
return -1;
}
} else {
ident = ALOOPER_POLL_CALLBACK;
}
int epollEvents = 0;
if (events & ALOOPER_EVENT_INPUT) epollEvents |= EPOLLIN;
if (events & ALOOPER_EVENT_OUTPUT) epollEvents |= EPOLLOUT;
{
AutoMutex _l(mLock);
Request request;
request.fd = fd;
request.ident = ident;
request.callback = callback;
request.data = data;
struct epoll_event eventItem;
memset(& eventItem, 0, sizeof(epoll_event));
eventItem.events = epollEvents;
eventItem.data.fd = fd;
ssize_t requestIndex = mRequests.indexOfKey(fd);
if (requestIndex < 0) {
int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, & eventItem);
if (epollResult < 0) {
ALOGE("Error adding epoll events for fd %d, errno=%d", fd, errno);
return -1;
}
mRequests.add(fd, request);
} else {
int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_MOD, fd, & eventItem);
if (epollResult < 0) {
ALOGE("Error modifying epoll events for fd %d, errno=%d", fd, errno);
return -1;
}
mRequests.replaceValueAt(requestIndex, request);
}
}
return 1;
}
如果 callback 為空,會檢查 mAllowNonCallbacks 是否允許 callback 為空;若允許,還會檢測 ident 是否 >=0。如果 callback 不為空,則會把 ident 的值賦為 ALOOPER_POLL_CALLBACK,無論傳進來的是什麼值。接著把傳入的參數封裝到一個 Request 結構體中,並以描述符為鍵保存到 KeyedVector mRequests 中,然後通過 epoll_ctl 添加或替換對該描述符事件的監聽。
類圖:

通過 Looper.prepare 初始化好消息隊列後,就可以調用 Looper.loop 進入消息循環,此後我們就能向消息隊列發送消息,消息循環會取出消息進行處理。在講消息處理之前,先看消息是怎麼被添加到消息隊列的。
在 Java 層,Message 類表示一個消息對象。要發送消息首先要獲得一個消息對象。Message 類的構造函數是 public 的,但不建議直接 new Message,因為 Message 內部保存了一個緩存的消息池,我們可以用 obtain 從緩存池獲得消息,使用完後系統會調用 recycle 回收。如果自己 new 很多 Message,用完後又放入緩存池,反而會佔用更多內存:
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
sPoolSize--;
return m;
}
}
return new Message();
}
public void recycle() {
clearForRecycle();
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
Message 內部通過 next 成員實現了一個鏈表,這樣 sPool 就成為了一個 Messages 的緩存鏈表。
獲取到消息對象後怎麼發送呢?大家都知道是通過 Handler 的 post、sendMessage 等方法,而這些方法最終都是調用同一個方法 sendMessageAtTime:
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);
}
sendMessageAtTime 獲取到消息隊列後調用 enqueueMessage 方法,消息隊列 mQueue 是從與 Handler 關聯的 Looper 獲得的。
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
enqueueMessage 把 message 的 target 設置為當前 handler,然後調用 MessageQueue 的 enqueueMessage。在調用之前判斷了 mAsynchronous,從名字看是異步消息的意思。要理解 Asynchronous 的作用,需要先了解一個概念——Barrier。
Barrier 從名字看是一個「攔截器」,在它後面的消息都暫時無法執行,直到這個攔截器被移除。MessageQueue 有一個函數 enqueueSyncBarrier 可以添加一個 Barrier:
int enqueueSyncBarrier(long when) {
synchronized (this) {
final int token = mNextBarrierToken++;
final Message msg = Message.obtain();
msg.arg1 = token;
Message prev = null;
Message p = mMessages;
if (when != 0) {
while (p != null && p.when <= when) {
prev = p;
p = p.next;
}
}
if (prev != null) {
msg.next = p;
prev.next = msg;
} else {
msg.next = p;
mMessages = msg;
}
return token;
}
}
在 enqueueSyncBarrier 中 obtain 了一個 Message,並設置 msg.arg1 = token(token 僅是一個每次調用時自增的 int 值,目的是保證每次調用返回唯一 token),這個 Message 同樣需要設置執行時間,然後插入到消息隊列。特殊的是,這個 Message 沒有設置 target,即 msg.target 為 null。
進入消息循環後會不停地從 MessageQueue 中取消息執行,調用的是 MessageQueue 的 next 函數,其中有這麼一段:
Message msg = mMessages;
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
如果隊列頭部的消息 target 為 null,就表示它是個 Barrier,因為只有兩種方法往 mMessages 中添加消息:一種是 enqueueMessage,另一種是 enqueueBarrier,而 enqueueMessage 中若 msg.target 為 null 是直接拋異常的。
所謂的異步消息其實就是這樣:我們可以通過 enqueueBarrier 往消息隊列插入一個 Barrier,那麼隊列中執行時間在這個 Barrier 以後的同步消息都會被攔截住無法執行,直到調用 removeBarrier 移除它;而异步消息則不受影響。消息默認就是同步消息,除非調用了 Message 的 setAsynchronous(這個方法是隱藏的)。只有在初始化 Handler 時通過參數指定往這個 Handler 發送的消息都是異步的,這樣 Handler 的 enqueueMessage 中就會調用 setAsynchronous 設置消息為異步。
也就是說,異步消息只有一個作用:在設置 Barrier 時仍可以不受 Barrier 影響被正常處理。如果沒有設置 Barrier,異步消息就與同步消息沒有區別。可以通過 removeSyncBarrier 移除 Barrier:
void removeSyncBarrier(int token) {
final boolean needWake;
synchronized (this) {
Message prev = null;
Message p = mMessages;
while (p != null && (p.target != null || p.arg1 != token)) {
prev = p;
p = p.next;
}
if (p == null) {
throw new IllegalStateException("The specified message queue synchronization barrier token has not been posted or has already been removed.");
}
if (prev != null) {
prev.next = p.next;
needWake = false;
} else {
mMessages = p.next;
needWake = mMessages == null || mMessages.target != null;
}
p.recycle();
}
if (needWake) {
nativeWake(mPtr);
}
}
參數 token 就是 enqueueSyncBarrier 的返回值,若指定的 token 不存在則會拋異常。
接下來看 MessageQueue 的 enqueueMessage:
final boolean enqueueMessage(Message msg, long when) {
if (msg.isInUse()) {
throw new AndroidRuntimeException(msg + " This message is already in use.");
}
if (msg.target == null) {
throw new AndroidRuntimeException("Message must have a target.");
}
boolean needWake;
synchronized (this) {
if (mQuiting) {
RuntimeException e = new RuntimeException(msg.target + " sending message to a Handler on a dead thread");
Log.w("MessageQueue", e.getMessage(), e);
return false;
}
msg.when = when;
Message p = mMessages;
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;
prev.next = msg;
}
}
if (needWake) {
nativeWake(mPtr);
}
return true;
}
注意標紅部分:當 msg.target 為 null 時是直接拋異常的。在 enqueueMessage 中首先判斷:如果當前消息隊列為空,或新消息的執行時間 when 為 0,或新消息的執行時間比隊列頭消息還早,就把消息添加到隊列頭(消息隊列按時間排序);否則要找到合適的位置插入。
消息模型不只是 Java 層用,Native 層也可以用。前面也看到了消息隊列初始化時同時初始化了 Native 層的 Looper 與 NativeMessageQueue,所以 Native 層也應該能發送消息。與 Java 層不同的是,Native 層是通過 Looper 發消息的,同樣所有發送方法最終都調用 sendMessageAtTime:
void Looper::sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler, const Message& message) {
size_t i = 0;
{
AutoMutex _l(mLock);
size_t messageCount = mMessageEnvelopes.size();
while (i < messageCount && uptime >= mMessageEnvelopes.itemAt(i).uptime) {
i += 1;
}
MessageEnvelope messageEnvelope(uptime, handler, message);
mMessageEnvelopes.insertAt(messageEnvelope, i, 1);
if (mSendingMessage) {
return;
}
}
// Wake the poll loop only when we enqueue a new message at the head.
if (i == 0) {
wake();
}
}
Native Message 只有一個 int 型的 what 字段用來區分不同消息。sendMessageAtTime 指定了 Message、執行時間 when 與處理消息的 MessageHandler,然後用 MessageEnvelope 封裝了 time、MessageHandler 與 Message。Native 層發的消息都保存到 mMessageEnvelopes 中,它是個 Vector,同樣按時間排序,與 Java 層的消息分別保存在兩個隊列裡。
消息隊列初始化好了,也知道怎麼發消息了,下面看怎麼處理消息,也就是 Handler.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;
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(msg);
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed while dispatching to " + msg.target.getClass().getName() + " " + msg.callback + " what=" + msg.what);
}
msg.recycle();
}
}
loop 每次從 MessageQueue 取出一個 Message,調用 msg.target.dispatchMessage(msg)。target 就是發送 message 時跟 message 關聯的 handler,這樣就調用到了熟悉的 dispatchMessage。Message 被處理後會被 recycle。當 queue.next 返回 null 時會退出消息循環。接下來看 MessageQueue.next 是怎麼取出消息的,又會在什麼時候返回 null:
final Message next() {
int pendingIdleHandlerCount = -1;
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(mPtr, nextPollTimeoutMillis);
synchronized (this) {
if (mQuiting) {
return null;
}
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
msg.markInUse();
return msg;
}
} else {
nextPollTimeoutMillis = -1;
}
if (pendingIdleHandlerCount < 0 && (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null;
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf("MessageQueue", "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
pendingIdleHandlerCount = 0;
nextPollTimeoutMillis = 0;
}
}
MessageQueue.next 首先調用 nativePollOnce,然後如果 mQuiting 為 true 就返回 null,Looper 就會退出消息循環。接著取隊列頭部消息,如果頭部消息是 Barrier(target==null)就往後遍歷找到第一個異步消息。接下來檢測獲取到的消息:如果為 null 表示沒有消息要執行,設置 nextPollTimeoutMillis = -1;否則檢測這個消息要執行的時間,若到時間了就 markInUse 並從隊列移除,然後返回;否則設置 nextPollTimeoutMillis 為距離最近要執行的消息還需要多久。無論當前沒有消息可執行還是頭部消息未到執行時間,都會執行後面的代碼看有沒有 IdleHandler,若有就運行;當 IdleHandler 被執行後會把 nextPollTimeoutMillis 設為 0。
nativePollOnce 是 native 方法,通過 JNI 最終調到 Native Looper::pollOnce,並從 Java 層傳入了 nextPollTimeoutMillis,即 Java 層消息隊列中執行時間最近的消息還要多久到執行時間:
int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
int result = 0;
for (;;) {
while (mResponseIndex < mResponses.size()) {
const Response& response = mResponses.itemAt(mResponseIndex++);
int ident = response.request.ident;
if (ident >= 0) {
int fd = response.request.fd;
int events = response.events;
void* data = response.request.data;
if (outFd != NULL) *outFd = fd;
if (outEvents != NULL) *outEvents = events;
if (outData != NULL) *outData = data;
return ident;
}
}
if (result != 0) {
if (outFd != NULL) *outFd = 0;
if (outEvents != NULL) *outEvents = 0;
if (outData != NULL) *outData = NULL;
return result;
}
result = pollInner(timeoutMillis);
}
}
再看 pollInner:
int Looper::pollInner(int timeoutMillis) {
// Adjust the timeout based on when the next message is due.
if (timeoutMillis != 0 && mNextMessageUptime != LLONG_MAX) {
nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);
if (messageTimeoutMillis >= 0 && (timeoutMillis < 0 || messageTimeoutMillis < timeoutMillis)) {
timeoutMillis = messageTimeoutMillis;
}
}
int result = ALOOPER_POLL_WAKE;
mResponses.clear();
mResponseIndex = 0;
struct epoll_event eventItems[EPOLL_MAX_EVENTS];
int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
mLock.lock();
if (eventCount < 0) {
if (errno == EINTR) {
goto Done;
}
result = ALOOPER_POLL_ERROR;
goto Done;
}
if (eventCount == 0) {
result = ALOOPER_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 == mWakeReadPipeFd) {
if (epollEvents & EPOLLIN) {
awoken();
}
} else {
ssize_t requestIndex = mRequests.indexOfKey(fd);
if (requestIndex >= 0) {
int events = 0;
if (epollEvents & EPOLLIN) events |= ALOOPER_EVENT_INPUT;
if (epollEvents & EPOLLOUT) events |= ALOOPER_EVENT_OUTPUT;
if (epollEvents & EPOLLERR) events |= ALOOPER_EVENT_ERROR;
if (epollEvents & EPOLLHUP) events |= ALOOPER_EVENT_HANGUP;
pushResponse(events, mRequests.valueAt(requestIndex));
}
}
}
Done:
mNextMessageUptime = LLONG_MAX;
while (mMessageEnvelopes.size() != 0) {
nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);
if (messageEnvelope.uptime <= now) {
{
sp<MessageHandler> handler = messageEnvelope.handler;
Message message = messageEnvelope.message;
mMessageEnvelopes.removeAt(0);
mSendingMessage = true;
mLock.unlock();
handler->handleMessage(message);
}
mLock.lock();
mSendingMessage = false;
result = ALOOPER_POLL_CALLBACK;
} else {
mNextMessageUptime = messageEnvelope.uptime;
break;
}
}
mLock.unlock();
for (size_t i = 0; i < mResponses.size(); i++) {
Response& response = mResponses.editItemAt(i);
if (response.request.ident == ALOOPER_POLL_CALLBACK) {
int fd = response.request.fd;
int events = response.events;
void* data = response.request.data;
int callbackResult = response.request.callback->handleEvent(fd, events, data);
if (callbackResult == 0) {
removeFd(fd);
}
response.request.callback.clear();
result = ALOOPER_POLL_CALLBACK;
}
}
return result;
}
可以說有兩個消息隊列:Java 層的消息保存在 Java 層 MessageQueue 的 mMessages 中,Native 層的消息保存在 Native Looper 的 mMessageEnvelopes 中,兩者都按時間排列。timeoutMillis 表示 Java 層下個要執行的消息還要多久執行,mNextMessageUptime 表示 Native 層下個要執行的消息還要多久執行。若 timeoutMillis 為 0,epoll_wait 不設置超時直接返回;若為 -1 說明 Java 層無消息,直接用 Native 的 timeout;否則 pollInner 取兩者最小值作為 timeout 調用 epoll_wait。當 epoll_wait 返回時可能有幾種情況:
若是前兩種情況直接 goto DONE。否則說明 FD 上有事件發生:如果是 mWakeReadPipeFd 的 EPOLLIN 事件就調用 awoken;否則就是通過 addFD 添加的 fd,在 addFD 中把要監聽的 fd 及其 events、callback、data 封裝成 Request 對象並以 fd 為鍵保存到 mRequests 中,於是在這裡以 fd 為鍵獲得 Request,並連同 events 通過 pushResponse 加入 mResponses 隊列(Response 僅是對 events 與 Request 的封裝)。
進入 DONE 部分後,從 mMessageEnvelopes 取出頭部的 Native 消息,如果到達了執行時間就調用它內部保存的 MessageHandler 的 handleMessage 處理並從隊列移除,設置 result 為 ALOOPER_POLL_CALLBACK,否則計算 mNextMessageUptime 表示 Native 消息隊列下一次消息要執行的時間。Native 消息是沒有 Barrier 與 Asynchronous 的。
最後遍歷 mResponses,如果 response.request.ident==ALOOPER_POLL_CALLBACK,就調用註冊的 callback 的 handleEvent 進行處理,然後從隊列移除。這次遍歷完之後,mResponses 中保留下來的就都是 ident>=0 並且 callback 為 NULL 的了。而在 NativeMessageQueue 初始化 Looper 時傳入了 mAllowNonCallbacks 為 false,所以這次處理完後 mResponses 一定為空。
回到 pollOnce,它是一個 for 循環。pollInner 中處理了所有 ident==ALOOPER_POLL_CALLBACK 的 Response,第二次進入 for 循環後如果 mResponses 不為空就可以找到 ident>0 的 Response,將其 ident 作為返回值返回由調用者自行處理。由於 pollInner 返回值不可能為 0(只可能為負數),所以 pollOnce 中的 for 循環只會執行兩次就返回了。Native Looper 也可以單獨使用,並有一個 prepare 函數,這時 mAllowNonCallbacks 可能為 true,pollOnce 中對 mResponses 的處理就有意義了。
在 Native Looper 的構造函數中,通過 pipe 打開了一個管道,並用 mWakeReadPipeFd 與 mWakeWritePipeFd 分別保存管道的讀端與寫端,然後用 epoll_ctl 監聽了讀端的 EPOLLIN 事件,在 pollInner 中通過 epoll_wait 讀取事件。那是在什麼時候往 mWakeWritePipeFd 寫,又是在什麼時候讀的 mWakeReadPipeFd 呢?在 Looper.cpp 中可以找到這兩個函數:
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);
}
}
}
void Looper::awoken() {
char buffer[16];
ssize_t nRead;
do {
nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
} while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
}
wake 函數向 mWakeWritePipeFd 寫入了一個 "W" 字符,awoken 從 mWakeReadPipeFd 讀取。往 mWakeWritePipeFd 寫數據只是為了讓 pollInner 中的 epoll_wait 能監聽到事件並返回。在 pollInner 中可以看到,如果是 mWakeReadPipeFd 的 EPOLLIN 事件,只是調用 awoken 消耗掉寫入的字符就往後處理了。
那什麼時候調用 wake 呢?在 sendMessageAtTime 即發送 Native Message 時,根據發送 Message 的執行時間查找 mMessageEnvelopes 計算應該插入的位置,如果是在頭部插入,就調用 wake 喚醒 epoll_wait。因為進入 pollInner 時根據 Java 層與 Native 層消息隊列頭部消息的執行時間計算出了一個 timeout,如果新消息是在頭部插入,說明它的執行時間至少在上述兩個消息中的一個之前,所以應該喚醒 epoll_wait。epoll_wait 返回後,檢查 Native 消息隊列,看頭部消息(即剛插入的消息)是否到執行時間了,到了就執行,否則就可能需要設置新的 timeout。
同樣在 Java 層的 MessageQueue 中,有一個函數 nativeWake 也同樣可以通過 JNI 調用 wake,調用的時機與 Native 類似:在消息隊列頭部插入消息,還有一種情況是消息隊列頭部是一個 Barrier,而且插入的消息是第一個異步消息。
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 {
// 如果頭部是 Barrier 並且新消息是異步消息則"有可能"需要喚醒
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;
prev.next = msg;
}
在頭部插入消息不一定調用 nativeWake,因為之前可能正在執行 IdleHandler。如果執行了 IdleHandler,就在其執行後把 nextPollTimeoutMillis 設置為 0,下次進入 for 循環就用 0 調用 nativePollOnce,不需要 wake;只有在沒有消息可執行(消息隊列為空或沒到執行時間)並且沒有設置 IdleHandler 時 mBlocked 才會為 true。
如果 Java 層的消息隊列被 Barrier Block 住了,並且當前插入的是一個異步消息,有可能需要喚醒 Looper,因為異步消息可以在 Barrier 下執行,但這個異步消息一定要是執行時間最早的異步消息。此外,退出 Looper 也需要 wake,removeSyncBarrier 時也可能需要。
SlidingMenu 側滑菜單實作:Fragment + ViewPager 打造經典側邊欄
SlidingMenu 側滑菜單實作:Fragment + ViewPager 打造經典側邊欄 側滑菜單是早期 Android 應用中非常經典的交互模式。本文將以 Sli
選擇排序:原理、實現與特點
選擇排序:原理、實現與特點基本思想選擇排序是一種直觀的排序算法。它的核心思想是:每一輪都從未排序部分中選擇最小元素,然後把它放到已排序部分的末尾。隨著每一輪選擇,未排序範
Linux 2.6 內核協議棧系列:TCP 協議之數據發送
深入 Linux 2.6 內核 TCP 數據發送機制 在探討 TCP 發送函數之前,必須先認識一個關鍵結構 sk_buff。在 Linux 內核中,sk_buff 結構代
Android 架構設計閒談(四):消息與數據究竟怎麼流動
Android 架構設計閒談(四):消息與數據究竟怎麼流動 前面幾篇分別談了模塊劃分、模塊組合與五視圖法的運用。這一篇要說的是整個應用裡消息與數據到底怎麼跑、怎麼循環,算