Android的消息機制學習(一)Looper,Handler,MessageQueue

Message,Handler是在Android中最常用的,更新UI點手段。與其他圖形界面的原理類似,Android系統中UI也是靠消息驅動來工作的,具體有以下一些概念。
消息發送者:發生消息到隊列
消息隊列:存儲消息的隊列
消息循環:不斷的循環取出消息,發給處理者
消息處理者:處理消息
他們的關係可以畫成下圖的樣子:



消息機制原理圖



消息循環Looper

Android消息循環由Looper類來實現。使用Looper要經過以下兩個方法。
Looper.prepare();
Looper.loop();
在Activity主線程中查看就有Looper的初始化,查看ActivityThread類的main方法中,有下列代碼



查看prepareMainLooper()方法第一句就調用了prepare方法。歸根結底Looper的調用順序先要調用prepare方法,然後再調用loop()方法。


1.Looper.prepare()
那我們先查看Looper的prepare方法
// sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

private static void prepare(boolean quitAllowed) {
    // 保證一個線程Looper只能調用一次
    // ThreadLocal並不是一個Thread,而是Thread的局部變量,
    // 也許把它命名爲ThreadLocalVariable更容易讓人理解一些。
    if (sThreadLocal.get() != null) {
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    sThreadLocal.set(new Looper(quitAllowed));
}
該方法很簡單就是創建了一個Looper對象存入sThreadLocal中。
注意:ThreadLocal調用set存儲,調用get獲取。普通對象當在不同線程中獲取時候是同一個對象,數據相同。然而ThreadLocal不同線程調用這個get,set獲取到的數據是不同的,它是線程相關的局部變量。
綜上一個線程只能存儲一個Looper對象。

查看下Looper的構造函數。
private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}
構造函數主要就是創建了一個MessageQueue。
用圖概括下

Looper.prepare()工作流程

prepare方法主要就是創建了Looper對象存在當前線程,同時Looper內創建了一個MessageQueue。
1.Looper.loop()
先看loop的源碼
public static void loop() {
    //取出當前線程相關的looper對象
    final Looper me = myLooper();
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }

    //獲取當前線程Looper對象內的MessageQueue(消息隊列)
    final MessageQueue queue = me.mQueue;

    // Make sure the identity of this thread is that of the local process,
    // and keep track of what that identity token actually is.
    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;
        }

        // This must be in a local variable, in case a UI event sets the logger
        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);
        }

        // Make sure that during the course of dispatching the
        // identity of the thread wasn't corrupted.
        final long newIdent = Binder.clearCallingIdentity();
        if (ident != newIdent) {
            Log.wtf(TAG, "Thread identity changed from 0x"
                    + Long.toHexString(ident) + " to 0x"
                    + Long.toHexString(newIdent) + " while dispatching to "
                    + msg.target.getClass().getName() + " "
                    + msg.callback + " what=" + msg.what);
        }

        msg.recycleUnchecked();
    }
}
查看loop方法,主要就是開啓了消息循環,內部就是一個for循環一直獲取一個個的Message調用msg.target.dispatchMessage處理。
1.獲取調用線程的Looper對象,獲取Looper對象內的MessageQueue
2.循環調用MessageQueue的next方法獲取下一個元素
3.最終調用target的dispatchMessage方法處理Message。
4.繼續步驟2

Looper.loop()工作流程

消息隊列MessageQueue

MessageQueue主要提供了向隊列插入Message的方法,獲取下一個Message的方法。其類內部的成員變量
final MessageQueue mQueue;
爲一個鏈表,存儲所有的Message看下Message鏈表的結構應該是下圖的樣子

整個隊列按照when變量從小到大排序,next變量指向下一個節點,其中的callback與target是消息最終的處理者。
上一節主要講了loop方法內有個for循環,for內部會一直獲取下一條Message。這裏就看以下這個next方法。
MessageQueue的next方法是獲取隊列中的下一條Message
Message next() {
    // Return here if the message loop has already quit and been disposed.
    // This can happen if the application tries to restart a looper after quit
    // which is not supported.
    final long ptr = mPtr;//保存的是c++層的MessageQueue指針 供native層使用
    if (ptr == 0) {
        return null;
    }

    int pendingIdleHandlerCount = -1; // -1 only during first iteration
    int nextPollTimeoutMillis = 0;
    for (;;) {
        if (nextPollTimeoutMillis != 0) {
            Binder.flushPendingCommands();
        }

        nativePollOnce(ptr, nextPollTimeoutMillis);//調用到c++層方法,可能阻塞在這裏

        synchronized (this) {
            // Try to retrieve the next message.  Return if found.
            final long now = SystemClock.uptimeMillis();
            Message prevMsg = null;
            Message msg = mMessages;
            if (msg != null && msg.target == null) {
                //target爲null則是作爲一個分隔符,普通的Message不返回,則向下遍歷直到一個異步的message
                // 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) {
                    //msg當前時間小於msg派發的時間,則計算當前到派發時間還需要多久 可能由於某種原因nativePollOnce返回,例如新插入了Message
                    // Next message is not ready.  Set a timeout to wake up when it is ready.
                    nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                } else {
                    // Got a message.
                    //獲得一個Message返回
                    mBlocked = false;
                    if (prevMsg != null) {
                        prevMsg.next = msg.next;
                    } else {
                        mMessages = msg.next;
                    }
                    msg.next = null;
                    msg.markInUse();
                    return msg;
                }
            } else {
                // No more messages.
                nextPollTimeoutMillis = -1;
            }

            // Process the quit message now that all pending messages have been handled.
            if (mQuitting) {
                dispose();
                return null;
            }

            // If first time idle, then get the number of idlers to run.
            // Idle handles only run if the queue is empty or if the first message
            // in the queue (possibly a barrier) is due to be handled in the future.
            //Message隊列爲空或者還沒有到隊列頭部的Message派發時間 則執行下idel
            if (pendingIdleHandlerCount < 0
                    && (mMessages == null || now < mMessages.when)) {
                pendingIdleHandlerCount = mIdleHandlers.size();
            }
            if (pendingIdleHandlerCount <= 0) {
                //如果idle數目小於等於0 則進入下一次循環
                // No idle handlers to run.  Loop and wait some more.
                mBlocked = true;
                continue;
            }

            if (mPendingIdleHandlers == null) {
                mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
            }
            mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
        }


        // Run the idle handlers.
        // We only ever reach this code block during the first iteration.
        for (int i = 0; i < pendingIdleHandlerCount; i++) {
            final IdleHandler idler = mPendingIdleHandlers[i];
            mPendingIdleHandlers[i] = null; // release the reference to the handler

            boolean keep = false;
            try {
                keep = idler.queueIdle();
            } catch (Throwable t) {
                Log.wtf(TAG, "IdleHandler threw exception", t);
            }

            if (!keep) {
                synchronized (this) {
                    mIdleHandlers.remove(idler);
                }
            }
        }

        // Reset the idle handler count to 0 so we do not run them again.
        pendingIdleHandlerCount = 0;

        // While calling an idle handler, a new message could have been delivered
        // so go back and look again for a pending message without waiting.
        nextPollTimeoutMillis = 0;
    }
}
這個next方法看似複雜,我們仔細梳理下它的條理。看看都做了什麼
1.如果獲取不到消息,讓線程阻塞
2.如果有delay的Message,我們應該讓阻塞一個定長的時間
3.如果有新的Message插入,應該重新調節阻塞時間
4.有一種特殊的Message是target爲null。用來阻塞同步的Message
5.在空閒時間(隊列爲空,阻塞之前),執行些其他操作,比如垃圾回收。
MessageQueue中的一些native方法。
private native static long nativeInit();
private native void nativePollOnce(long ptr, int timeoutMillis); /*non-static for callbacks*/
private native static void nativeWake(long ptr);
在看next方法的時候首先會遇到一個nativePollOnce方法,這裏先說下它的功能。
nativePollOnce方法是個native方法,它的功能主要是讓線程阻塞,第一個參數是native的MessageQueue指針,第二個參數比較重要,是需要阻塞的時間
當爲-1的時候標誌永久阻塞,爲0的時候立刻返回,爲正數的時候表示要阻塞的時間。
nativePollOnce方法阻塞的時候,其實是可以被喚醒的,
nativeWake方法被調用的時候,nativePollOnce就會被喚醒。
next方法裏邊有個for循環,這個函數裏的for循環並不是起循環獲取消息的作用,而是當阻塞的時候被喚醒,再次進入上述next流程,以便能返回一個Message,或者重新計算阻塞時間。
看下阻塞時間nextPollTimeoutMillis賦值的幾種情況。
1.new<msg.when即當前時間還沒到Message的派發時間呢,我們需要重新計算下一個Message的發生時間,這是因爲我們在向隊列插入新的Message的時候可能引起隊列中按時間排序的鏈表的變化,獲取的下一個Message可能已經不是上次循環的那個Message了
2.當獲取的下一條Message爲null,nextPollTimeoutMillis賦值爲-1,這時候線程將永遠阻塞,直到被nativeWake喚醒,一般在向隊列中插入Message需要喚醒處理。
3.當idleHandler被處理之後nextPollTimeoutMillis賦值爲0,由於idleHandler可能是耗時處理,完成後可能已經有Message到了發生時間了。

代碼節選,這個分支處理是next 的核心邏輯
if (msg != null) {
    if (now < msg.when) {
        //msg當前時間小於msg派發的時間,則計算當前到派發時間還需要多久 可能由於某種原因nativePollOnce返回,例如新插入了Message
        // Next message is not ready.  Set a timeout to wake up when it is ready.
        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
    } else {
        // Got a message.
        //獲得一個Message返回
        mBlocked = false;
        if (prevMsg != null) {
            prevMsg.next = msg.next;
        } else {
            mMessages = msg.next;
        }
        msg.next = null;
        msg.markInUse();
        return msg;
    }
} else {
    // No more messages.
    nextPollTimeoutMillis = -1;
}
idle的處理:
在ActivityThread中,在某種情況下會在消息隊列中設置GcIdler,進行垃圾收集,其定義如下:
final class GcIdler implements MessageQueue.IdleHandler {
    @Override
    public final boolean queueIdle() {
        doGcIfNeeded();
        return false;
    }
}
一旦隊列裏設置了這個Idle Handler,那麼當隊列中沒有馬上需處理的消息時,就會進行垃圾收集。

綜上中next方法流程如下


向隊列中插入Message,要保證按時間排序,要處理分隔符Message,處理異步Message,看下插入的方法enqueueMessage。
boolean enqueueMessage(Message msg, long when) {
    if (msg.target == null) {
        throw new IllegalArgumentException("Message must have a target.");
    }
    if (msg.isInUse()) {
        throw new IllegalStateException(msg + " This message is already in use.");
    }

    synchronized (this) {
        if (mQuitting) {
            IllegalStateException e = new IllegalStateException(
                    msg.target + " sending message to a Handler on a dead thread");
            Log.w(TAG, e.getMessage(), e);
            msg.recycle();
            return false;
        }

        msg.markInUse();
        msg.when = when;
        Message p = mMessages;
        boolean needWake;
        //正式開始插入邏輯
        if (p == null || when == 0 || when < p.when) {
            //這裏是直接插入隊列頭部, 需要喚醒next方法的阻塞 進行下一次循環
            // New head, wake up the event queue if blocked.
            msg.next = p;
            mMessages = msg;
            needWake = mBlocked;
        } else {
            // Inserted within the middle of the queue.  Usually we don't have to wake
            // up the event queue unless there is a barrier at the head of the queue
            // and the message is the earliest asynchronous message in the queue.
            //插入隊列中間.通常不需要喚醒next方法 當遇隊列首個Message爲分隔欄,且插入的Message爲異步的需要喚醒 目的是讓這個異步的Message接受處理
            needWake = mBlocked && p.target == null && msg.isAsynchronous();
            Message prev;
            //根據when遍歷到合適的位置插入Message
            for (;;) {
                prev = p;
                p = p.next;
                if (p == null || when < p.when) {
                    break;
                }
                //當前的Message是異步消息,並且不是第一個,不用喚醒了
                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中存儲的是一個根據when字段從小到大排列的有序鏈表,向隊列中插入數據,其實就是根據when字段把Message插入到鏈表的合適的位置。根據插入情況決定是否喚醒next方法。一般插入鏈表頭部需要喚醒,因爲頭部剛插入的這個Message變成了下一個要執行的,需要知道他的狀態,然後進行定時阻塞,或者直接返回。

Message分析

Message大概有三種:
普通Message
target變量爲發送Message的Handler自己
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}
Handler的enqueueMessage方法中第一句對msg的target進行了賦值

異步Message
通過Message的setAsynchronous方法來設置是否是異步Message,isAsynchronous方法來判斷是否是異步Message,普通創建的Message爲同步的
int flags;
public boolean isAsynchronous() {
    return (flags & FLAG_ASYNCHRONOUS) != 0;
}
public void setAsynchronous(boolean async) {
    if (async) {
        flags |= FLAG_ASYNCHRONOUS;
    } else {
        flags &= ~FLAG_ASYNCHRONOUS;
    }
}
handler構造函數提供了一個參數,async來決,向隊列插入的Message是否是異步Message
public Handler(Callback callback, boolean async)
public Handler(Looper looper, Callback callback, boolean async)
Message分隔符
上次多次提到了target爲null的Message,它始終特殊的Message,在隊列中作爲一個分隔符,以他爲標誌,後邊的同步的Message將不會被looper處理。
看下MessageQueue的定義,這種Message只能通過MessageQueue的下列方法打入隊列,不能自己直接構造Message打入隊列。
MessageQueue提供了postSyncBarrier方法用於向隊列中打入”分隔符”。
removeSyncBarrier方法用於移除隊列中的”分隔符"
詳細見以下源碼
public int postSyncBarrier() {
    return postSyncBarrier(SystemClock.uptimeMillis());
}

private int postSyncBarrier(long when) {
    // Enqueue a new sync barrier token.
    // We don't need to wake the queue because the purpose of a barrier is to stall it.
    synchronized (this) {
        final int token = mNextBarrierToken++;
        final Message msg = Message.obtain();
        msg.markInUse();
        msg.when = when;
        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) { // invariant: p == prev.next
            msg.next = p;
            prev.next = msg;
        } else {
            msg.next = p;
            mMessages = msg;
        }
        return token;
    }
}

/**
 * Removes a synchronization barrier.
 *
 * @param token The synchronization barrier token that was returned by
 * {@link #postSyncBarrier}.
 *
 * @throws IllegalStateException if the barrier was not found.
 *
 * @hide
 */
public void removeSyncBarrier(int token) {
    // Remove a sync barrier token from the queue.
    // If the queue is no longer stalled by a barrier then wake it.
    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.");
        }
        final boolean needWake;
        if (prev != null) {
            prev.next = p.next;
            needWake = false;
        } else {
            mMessages = p.next;
            needWake = mMessages == null || mMessages.target != null;
        }
        p.recycleUnchecked();

        // If the loop is quitting then it is already awake.
        // We can assume mPtr != 0 when mQuitting is false.
        if (needWake && !mQuitting) {
            nativeWake(mPtr);
        }
    }
}


把所有的Message畫入MessageQueue中如上圖

處理者&發送者Handler

Handler主要封裝了向MessageQueue添加Message的與處理Message的方法,讓對MessageQueue的操作更簡單
查看Handler中的成員變量,主要有以下兩個
final MessageQueue mQueue;
final Looper mLooper;
然後看下構造函數,看看他們的初始化過程
public Handler(Callback callback, boolean async) {
    if (FIND_POTENTIAL_LEAKS) {
        final Class<? extends Handler> klass = getClass();
        if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                (klass.getModifiers() & Modifier.STATIC) == 0) {
            Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                klass.getCanonicalName());
        }
    }

    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;
}

public Handler(Looper looper, Callback callback, boolean async) {
    mLooper = looper;
    mQueue = looper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}
主要有上邊兩個構造函數,第一個構造函數,獲取當前線程的Looper對象與MessageQueue存儲起來。
第二個構造函數,主要是從外部傳入一個Looper對象,可以是其他線程Looper對象,然後存儲這個Looper與他的MessageQueue

想想Handler的常用方法,一般會調用sendMessage,sendMessageDelayed,post的等相關方法發送一個Message,然後通過handler的handleMessage方法處理.

通過查詢源碼發現這些發送消息的方法都會調用Handler的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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}
原來最終是調用了MessageQueue的enqueueMessage方法,向隊列插入消息,同時注意此時msg.target設置爲了Handler自己。畫圖概括下發送消息的過程。

從第二個構造函數可知道,Handler內可以傳入一個Looper對象,這樣就可以傳入其他線程的Looper,這樣通過這個Handler就可以向其他線程消息循環發送Message了。
同時Handler也承擔了處理Message的角色。上邊說了在Looper的loop方法中,會一直循環獲取MessageQueue的下一條消息處理,處理是調用
msg.target.dispatchMessage(msg);
target就是Handler類型,最終調用Handler的dispatchMessage方法處理消息
public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}
dispatchMessage中定義了一套消息處理優先級的機制
1.Message自己的callback,這種處理一般用在post相關方法發送消息的情況較多,例如post(new Runnable(){ run(){...} }) 。
2.Handler設置的全局callback,不常用。
3.交給Handler的handleMessage處理,通常需要子類中重寫該方法來完成工作 

至此JAVA已經分析完畢,知道那幾個native方法的作用,不想了解他的原理,不看下邊內容也可以。

Native層分析

我們這裏主要遇到了下邊幾個native方法
private native static long nativeInit();
private native void nativePollOnce(long ptr, int timeoutMillis); /*non-static for callbacks*/
private native static void nativeWake(long ptr);
上述方法的native實現在
[/frameworks/base/core/jni/android_os_MessageQueue.cpp]
static JNINativeMethod gMessageQueueMethods[] = {
/* name, signature, funcPtr */
    {"nativeInit", "()J", (void*)android_os_MessageQueue_nativeInit},
    {"nativeDestroy","(J)V",(void*)android_os_MessageQueue_nativeDestroy},
    {"nativePollOnce","(JI)V",(void*)android_os_MessageQueue_nativePollOnce},
    {"nativeWake","(J)V",(void*)android_os_MessageQueue_nativeWake},
    {"nativeIsPolling","(J)Z",(void*)android_os_MessageQueue_nativeIsPolling},
    {"nativeSetFileDescriptorEvents","(JII)V",
    (void*)android_os_MessageQueue_nativeSetFileDescriptorEvents},
    };
}
這裏看下android_os_MessageQueue方法
[/frameworks/base/core/jni/android_os_MessageQueue.cpp]
static jlong android_os_MessageQueue_nativeInit(JNIEnv* env, jclass clazz) {
    NativeMessageQueue* nativeMessageQueue = new NativeMessageQueue();
    if (!nativeMessageQueue) {
        jniThrowRuntimeException(env, "Unable to allocate native queue");
        return 0;
    }

    nativeMessageQueue->incStrong(env);
    return reinterpret_cast<jlong>(nativeMessageQueue);
}
這個方法裏邊創建了一個nativeMessageQueue,繼續看NativeMessageQueue的構造函數
[/frameworks/base/core/jni/android_os_MessageQueue.cpp]
NativeMessageQueue::NativeMessageQueue() :
mPollEnv(NULL), mPollObj(NULL), mExceptionObj(NULL) {
    mLooper = Looper::getForThread();
    if (mLooper == NULL) {
        mLooper = new Looper(false);
        Looper::setForThread(mLooper);
    }
}
在NativeMessageQueue的構造函數中創建了一個Looper對象,這個Looper是native層的,定義在/system/core/include/utils/Looper.h文件中
class Looper : public RefBase{
    protected:
            virtual~Looper();
    public:
            .......
            Looper(bool allowNonCallbacks);
            bool getAllowNonCallbacks()const;
            int pollOnce(int timeoutMillis,int*outFd,int*outEvents,void**outData);
            inline int pollOnce(int timeoutMillis){
            return pollOnce(timeoutMillis,NULL,NULL,NULL);
            }
            .....
            void wake();
            int addFd(int fd,int ident,int events,Looper_callbackFunc callback,void*data);
            int addFd(int fd,int ident,int events,const sp<LooperCallback>&callback,void*data);
            int removeFd(int fd);
            void sendMessage(const sp<MessageHandler>&handler,const Message&message);
            void sendMessageDelayed(nsecs_t uptimeDelay,const sp<MessageHandler>&handler,const Message&message);
            void sendMessageAtTime(nsecs_t uptime,const sp<MessageHandler>&handler,const Message&message);
            void removeMessages(const sp<MessageHandler>&handler);
            void removeMessages(const sp<MessageHandler>&handler,int what);
            .......
}
主要定義了一些fd與Message等操作的方法,和本地Message相關的變量,這裏不是着重分析,native的消息機制,主要分析下整個流程。

上邊的說到NativeMessageQueue的構造函數中,創建了一個Looper對象,看下Looper的構造函數都做了什麼。
查看Looper的構造函數
[/system/core/libutils/Looper.cpp]
Looper::Looper(bool allowNonCallbacks) :
mAllowNonCallbacks(allowNonCallbacks), mSendingMessage(false),
mPolling(false), mEpollFd(-1), mEpollRebuildRequired(false),
mNextRequestSeq(0), mResponseIndex(0), mNextMessageUptime(LLONG_MAX) {
    mWakeEventFd = eventfd(0, EFD_NONBLOCK);
    LOG_ALWAYS_FATAL_IF(mWakeEventFd < 0, "Could not make wake event fd.  errno=%d", errno);

    AutoMutex _l(mLock);
    rebuildEpollLocked();
}
首先初始化了一大堆變量,此處不重要略過,直接看eventfd方法創建的對象。
eventfd具體與pipe有點像,用來完成兩個線程之間事件觸發。這個函數會創建一個 事件對象 (eventfd object), 用來實現,進程(線程)間 的 等待/通知(wait/notify) 機制. 內核會爲這個對象維護一個64位的計數器(uint64_t)。並且使用第一個參數(initval)初始化這個計數器。調用這個函數就會返回一個新的文件描述符。
這個mWakeEventFd很重要,看下邊的rebuildEpollLocked方法

[/system/core/libutils/Looper.cpp]
void Looper::rebuildEpollLocked() {
    // Close old epoll instance if we have one.
    //如果創建了epoll,關閉epoll
    if (mEpollFd >= 0) {
        close(mEpollFd);
    }

    // Allocate the new epoll instance and register the wake pipe.
    // 創建一個epoll
    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)); // zero out unused members of data field union
    eventItem.events = EPOLLIN;//表示對應的文件描述符可以讀事件
    eventItem.data.fd = mWakeEventFd;//Looper構造函數中eventfd函數返回的文件描述符
    //註冊新的fd到epoll中 監聽文件可讀事件
    int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeEventFd, & eventItem);

    LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake event fd to epoll instance.  errno=%d",
            errno);

    for (size_t i = 0; i < mRequests.size(); i++) {//mRequests是個KeyedVector<int, Request>類型,遍歷每個Request對象,把他們一次加入epoll中監聽
        const Request& request = mRequests.valueAt(i);
        struct epoll_event eventItem;
        request.initEventItem(&eventItem);

        int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, request.fd, & eventItem);
        if (epollResult < 0) {
            ALOGE("Error adding epoll events for fd %d while rebuilding epoll set, errno=%d",
                    request.fd, errno);
        }
    }
}
這裏插入解釋下epoll的作用。
epoll
epoll 是Linux內核中的一種可擴展IO事件處理機制,epoll會把被監聽的文件發生了怎樣的I/O事件通知我們。
native層主要就是利用了Linux提供的epoll機制,大家仔細瞭解下這個系統調用的作用,native層就沒有什麼難點了。
看下epoll的三個函數作用
int epoll_create(int size)
創建一個epoll的句柄。
int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event)
epoll的事件註冊函數epoll的事件註冊函數
第一個參數是 epoll_create() 的返回值,第二個參數表示動作,第三個參數是需要監聽的fd,第四個參數是告訴內核需要監聽什麼事件
int epoll_wait(int epfd, struct epoll_event * events, int maxevents, int timeout)
等待事件的產生。參數events用來從內核得到事件的集合,maxevents表示每次能處理的最大事件數,告之內核這個events有多大,這個maxevents的值不能大於創建epoll_create()時的size,參數timeout是超時時間(毫秒,0會立即返回,-1將不確定,也有說法說是永久阻塞)。該函數返回需要處理的事件數目,如返回0表示已超時。

至此可以看到在構造Looper對象時,其內部除了創建了eventfd,還創建了一個epoll來監聽eventfd。也就是說,是利用epoll機制來完成阻塞動作的。每當java層調用nativeWake的時候,最終會間接向eventfd寫入數據,於是epoll立即就監聽到了文件變化,epoll_wait()在等到事件後,隨即進行相應的事件處理。這就是消息循環阻塞並處理的大體流程。
概括下nativeInit的流程:

nativePollOnce
在java層的next方法,首先調用的方法就是nativePollOnce 。然後看下native層的實現。nativePollOnce對應android_os_MessageQueue_nativePollOnce方法。看下這個方法。
[/frameworks/base/core/jni/android_os_MessageQueue.cpp]
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);
}
這裏ptr就是定義在java層,MessageQueue中成員變量mPtr,強轉成nativeMessageQueue
timeoutMillis就是java層中MessageQueue中傳入的阻塞時間
該方法中直接調用了nativeInit創建的那個nativeMessageQueue的pollOnce方法。
[/frameworks/base/core/jni/android_os_MessageQueue.cpp]
void NativeMessageQueue::pollOnce(JNIEnv* env, jobject pollObj, int timeoutMillis) {
    mPollEnv = env;
    mPollObj = pollObj;
    mLooper->pollOnce(timeoutMillis);
    mPollObj = NULL;
    mPollEnv = NULL;

    if (mExceptionObj) {
        env->Throw(mExceptionObj);
        env->DeleteLocalRef(mExceptionObj);
        mExceptionObj = NULL;
    }
}
pollOnce方法沒有做什麼,就是直接調用了Looper的pollOnce方法。
看下Looper的pollOnce方法
[/system/core/libutils/Looper.cpp]
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方法。這個方法比較長 ,主要注意epoll_wait方法,線程會阻塞在那裏,等待事件的發生。
[/system/core/libutils/Looper.cpp]
int Looper::pollInner(int timeoutMillis) {
    ......
   
    //阻塞在這裏,到時間或者有事件發生返回
    int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
    ......
    // Handle all events.
    //處理所有epoll事件
    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) {//當fd是eventfd且事件爲EPOLLIN 則執行awoke方法 內部只是讀取eventfd
                awoken();
            } else {
                ALOGW("Ignoring unexpected epoll events 0x%x on wake event fd.", epollEvents);
            }
        } else {//如果是其他事件 則把request加入到mResponses中
            ssize_t requestIndex = mRequests.indexOfKey(fd);
            if (requestIndex >= 0) {
                int events = 0;
                if (epollEvents & EPOLLIN) events |= EVENT_INPUT;
                if (epollEvents & EPOLLOUT) events |= EVENT_OUTPUT;
                if (epollEvents & EPOLLERR) events |= EVENT_ERROR;
                if (epollEvents & EPOLLHUP) events |= EVENT_HANGUP;
                //內部調用mResponses.push(response);
                pushResponse(events, mRequests.valueAt(requestIndex));
            } else {
                ALOGW("Ignoring unexpected epoll events 0x%x on fd %d that is "
                        "no longer registered.", epollEvents, fd);
            }
        }
    }
    Done: ;

    // Invoke pending message callbacks.
    mNextMessageUptime = LLONG_MAX;
    //native層也有自己的Message,可以調用Looper::sendMessage,Looper::sendMessageDelayed方法進行發送Message
    //發送出的Message會包裝在MessageEnvelope中 然後加入mMessageEnvelopes中
    //這裏會循環處理所有的native層的Message
    while (mMessageEnvelopes.size() != 0) {
        nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
        const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);
        if (messageEnvelope.uptime <= now) {
            // Remove the envelope from the list.
            // We keep a strong reference to the handler until the call to handleMessage
            // finishes.  Then we drop it so that the handler can be deleted *before*
            // we reacquire our lock.
            { // obtain handler
                sp<MessageHandler> handler = messageEnvelope.handler;
                Message message = messageEnvelope.message;
                mMessageEnvelopes.removeAt(0);
                mSendingMessage = true;
                mLock.unlock();
                //調用MessageHandler的回調
                handler->handleMessage(message);
            } // release handler

            mLock.lock();
            mSendingMessage = false;
            result = POLL_CALLBACK;
        } else {
            // The last message left at the head of the queue determines the next wakeup time.
            //根據現在的隊列頭部的Message的uptime決定下一次喚醒時間
            mNextMessageUptime = messageEnvelope.uptime;
            break;
        }
    }

    // Release lock.
    mLock.unlock();

    // Invoke all response callbacks.
    //處理response
    for (size_t i = 0; i < mResponses.size(); i++) {
        Response& response = mResponses.editItemAt(i);
        if (response.request.ident == POLL_CALLBACK) {
            int fd = response.request.fd;
            int events = response.events;
            void* data = response.request.data;

            // Invoke the callback.  Note that the file descriptor may be closed by
            // the callback (and potentially even reused) before the function returns so
            // we need to be a little careful when removing the file descriptor afterwards.
            int callbackResult = response.request.callback->handleEvent(fd, events, data);
            if (callbackResult == 0) {
                removeFd(fd, response.request.seq);
            }

            // Clear the callback reference in the response structure promptly because we
            // will not clear the response vector itself until the next poll.
            response.request.callback.clear();
            result = POLL_CALLBACK;
        }
    }
    return result;
}

默認系統只是創建了一個eventfd,等待他的事件發生,一進入上述方法可能回阻塞在epoll_wait方法,當eventfd有個風吹草動就回被喚醒,例如往裏邊寫點東西。當喚醒後就處理下,讀取eventfd裏的數據。剩下的代碼就是處理native層的Message隊列中的消息。所以當你在JAVA層發送一個Message可能不會立刻執行,因爲可能還在處理native層的消息。
可以看出JAVA層每次循環取出一個Message處理,而native層是每次把隊列中的消息一次性處理完。
nativeWake
看看最後一個方法nativeWake
這個方法比較簡單直接就是向下調用最後調用到了Looper的wake方法。
[/frameworks/base/core/jni/android_os_MessageQueue.cpp]
static void android_os_MessageQueue_nativeWake(JNIEnv* env, jclass clazz, jlong ptr) {
    NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
    nativeMessageQueue->wake();
}
[/frameworks/base/core/jni/android_os_MessageQueue.cpp]
void NativeMessageQueue::wake() {
    mLooper->wake();
}
[/system/core/libutils/Looper.cpp]
void Looper::wake() {
    uint64_t inc = 1;
    ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd, &inc, sizeof(uint64_t)));
    if (nWrite != sizeof(uint64_t)) {
        if (errno != EAGAIN) {
            ALOGW("Could not write wake signal, errno=%d", errno);
        }
    }
}
看看這個方法的功能,就是往mWakeEventFd裏,就是初始化的時候eventfd函數創建的文件,中寫入了一個uint64_t數字。因爲epoll監聽這個文件,所以epoll會立刻返回,這樣pollOnce就可以繼續向下執行了。


最後概括下native層之於JAVA層的作用:


發佈了30 篇原創文章 · 獲贊 62 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章