// sThreadLocal.get() will return null unless you've called prepare().該方法很簡單就是創建了一個Looper對象存入sThreadLocal中。 注意:ThreadLocal調用set存儲,調用get獲取。普通對象當在不同線程中獲取時候是同一個對象,數據相同。然而ThreadLocal不同線程調用這個get,set獲取到的數據是不同的,它是線程相關的局部變量。 綜上一個線程只能存儲一個Looper對象。
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));
}
private Looper(boolean quitAllowed) {構造函數主要就是創建了一個MessageQueue。 用圖概括下
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
public static void loop() {查看loop方法,主要就是開啟了消息循環,內部就是一個for循環一直獲取一個個的Message調用msg.target.dispatchMessage處理。 1.獲取調用線程的Looper對象,獲取Looper對象內的MessageQueue 2.循環調用MessageQueue的next方法獲取下一個元素 3.最終調用target的dispatchMessage方法處理Message。 4.繼續步驟2
//取出當前線程相關的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();
}
}
Message next() {這個next方法看似復雜,我們仔細梳理下它的條理。看看都做了什么 1.如果獲取不到消息,讓線程阻塞 2.如果有delay的Message,我們應該讓阻塞一個定長的時間 3.如果有新的Message插入,應該重新調節阻塞時間 4.有一種特殊的Message是target為null。用來阻塞同步的Message 5.在空閑時間(隊列為空,阻塞之前),執行些其他操作,比如垃圾回收。 MessageQueue中的一些native方法。
// 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;
}
}
private native static long nativeInit();在看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到了發生時間了。
private native void nativePollOnce(long ptr, int timeoutMillis); /*non-static for callbacks*/
private native static void nativeWake(long ptr);
if (msg != null) {idle的處理: 在ActivityThread中,在某種情況下會在消息隊列中設置GcIdler,進行垃圾收集,其定義如下:
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;
}
final class GcIdler implements MessageQueue.IdleHandler {一旦隊列里設置了這個Idle Handler,那么當隊列中沒有馬上需處理的消息時,就會進行垃圾收集。
@Override
public final boolean queueIdle() {
doGcIfNeeded();
return false;
}
}
boolean enqueueMessage(Message msg, long when) {由於MessageQueue中存儲的是一個根據when字段從小到大排列的有序鏈表,向隊列中插入數據,其實就是根據when字段把Message插入到鏈表的合適的位置。根據插入情況決定是否喚醒next方法。一般插入鏈表頭部需要喚醒,因為頭部剛插入的這個Message變成了下一個要執行的,需要知道他的狀態,然后進行定時阻塞,或者直接返回。
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;
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {Handler的enqueueMessage方法中第一句對msg的target進行了賦值
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
int flags;handler構造函數提供了一個參數,async來決,向隊列插入的Message是否是異步Message
public boolean isAsynchronous() {
return (flags & FLAG_ASYNCHRONOUS) != 0;
}
public void setAsynchronous(boolean async) {
if (async) {
flags |= FLAG_ASYNCHRONOUS;
} else {
flags &= ~FLAG_ASYNCHRONOUS;
}
}
public Handler(Callback callback, boolean async)Message分隔符 上次多次提到了target為null的Message,它始終特殊的Message,在隊列中作為一個分隔符,以他為標志,后邊的同步的Message將不會被looper處理。 看下MessageQueue的定義,這種Message只能通過MessageQueue的下列方法打入隊列,不能自己直接構造Message打入隊列。 MessageQueue提供了postSyncBarrier方法用於向隊列中打入”分隔符”。 removeSyncBarrier方法用於移除隊列中的”分隔符" 詳細見以下源碼
public Handler(Looper looper, Callback callback, boolean async)
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);
}
}
}
final MessageQueue mQueue;然后看下構造函數,看看他們的初始化過程
final Looper mLooper;
public Handler(Callback callback, boolean async) {主要有上邊兩個構造函數,第一個構造函數,獲取當前線程的Looper對象與MessageQueue存儲起來。第二個構造函數,主要是從外部傳入一個Looper對象,可以是其他線程Looper對象,然后存儲這個Looper與他的MessageQueue
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;
}
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {原來最終是調用了MessageQueue的enqueueMessage方法,向隊列插入消息,同時注意此時msg.target設置為了Handler自己。畫圖概括下發送消息的過程。
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);
}
public void dispatchMessage(Message msg) {dispatchMessage中定義了一套消息處理優先級的機制 1.Message自己的callback,這種處理一般用在post相關方法發送消息的情況較多,例如post(new Runnable(){ run(){...} }) 。 2.Handler設置的全局callback,不常用。 3.交給Handler的handleMessage處理,通常需要子類中重寫該方法來完成工作
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
private native static long nativeInit();上述方法的native實現在[/frameworks/base/core/jni/android_os_MessageQueue.cpp]
private native void nativePollOnce(long ptr, int timeoutMillis); /*non-static for callbacks*/
private native static void nativeWake(long ptr);
static JNINativeMethod gMessageQueueMethods[] = {這里看下android_os_MessageQueue方法[/frameworks/base/core/jni/android_os_MessageQueue.cpp]
/* 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},
};
}
static jlong android_os_MessageQueue_nativeInit(JNIEnv* env, jclass clazz) {這個方法里邊創建了一個nativeMessageQueue,繼續看NativeMessageQueue的構造函數[/frameworks/base/core/jni/android_os_MessageQueue.cpp]
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() :在NativeMessageQueue的構造函數中創建了一個Looper對象,這個Looper是native層的,定義在/system/core/include/utils/Looper.h文件中
mPollEnv(NULL), mPollObj(NULL), mExceptionObj(NULL) {
mLooper = Looper::getForThread();
if (mLooper == NULL) {
mLooper = new Looper(false);
Looper::setForThread(mLooper);
}
}
class Looper : public RefBase{主要定義了一些fd與Message等操作的方法,和本地Message相關的變量,這里不是着重分析,native的消息機制,主要分析下整個流程。
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);
.......
}
Looper::Looper(bool allowNonCallbacks) :首先初始化了一大堆變量,此處不重要略過,直接看eventfd方法創建的對象。eventfd具體與pipe有點像,用來完成兩個線程之間事件觸發。這個函數會創建一個 事件對象 (eventfd object), 用來實現,進程(線程)間 的 等待/通知(wait/notify) 機制. 內核會為這個對象維護一個64位的計數器(uint64_t)。並且使用第一個參數(initval)初始化這個計數器。調用這個函數就會返回一個新的文件描述符。這個mWakeEventFd很重要,看下邊的rebuildEpollLocked方法
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();
}
void Looper::rebuildEpollLocked() {這里插入解釋下epoll的作用。epollepoll 是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表示已超時。
// 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);
}
}
}
static void android_os_MessageQueue_nativePollOnce(JNIEnv* env, jobject obj,jlong ptr, jint timeoutMillis) {這里ptr就是定義在java層,MessageQueue中成員變量mPtr,強轉成nativeMessageQueuetimeoutMillis就是java層中MessageQueue中傳入的阻塞時間該方法中直接調用了nativeInit創建的那個nativeMessageQueue的pollOnce方法。[/frameworks/base/core/jni/android_os_MessageQueue.cpp]
NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
nativeMessageQueue->pollOnce(env, obj, timeoutMillis);
}
void NativeMessageQueue::pollOnce(JNIEnv* env, jobject pollObj, int timeoutMillis) {pollOnce方法沒有做什么,就是直接調用了Looper的pollOnce方法。看下Looper的pollOnce方法[/system/core/libutils/Looper.cpp]
mPollEnv = env;
mPollObj = pollObj;
mLooper->pollOnce(timeoutMillis);
mPollObj = NULL;
mPollEnv = NULL;
if (mExceptionObj) {
env->Throw(mExceptionObj);
env->DeleteLocalRef(mExceptionObj);
mExceptionObj = NULL;
}
}
int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {這里直接看最后一行,pollInner方法。這個方法比較長 ,主要注意epoll_wait方法,線程會阻塞在那里,等待事件的發生。[/system/core/libutils/Looper.cpp]
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);
}
}
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;
}
static void android_os_MessageQueue_nativeWake(JNIEnv* env, jclass clazz, jlong ptr) {[/frameworks/base/core/jni/android_os_MessageQueue.cpp]
NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
nativeMessageQueue->wake();
}
void NativeMessageQueue::wake() {[/system/core/libutils/Looper.cpp]
mLooper->wake();
}
void Looper::wake() {看看這個方法的功能,就是往mWakeEventFd里,就是初始化的時候eventfd函數創建的文件,中寫入了一個uint64_t數字。因為epoll監聽這個文件,所以epoll會立刻返回,這樣pollOnce就可以繼續向下執行了。
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);
}
}
}
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。