privatestaticvoidprepare(boolean quitAllowed) { if (sThreadLocal.get() != null) { //一个线程中Looper.prepare()只能执行一次,否则会抛出异常 thrownewRuntimeException("Only one Looper may be created per thread"); } //构造了一个Looper放到ThreadLocal中 sThreadLocal.set(newLooper(quitAllowed)); }
/** * Poll and deliver single message, return true if the outer loop should continue. */ privatestaticbooleanloopOnce(final Looper me, finallong ident, finalint thresholdOverride) { Messagemsg= me.mQueue.next(); // 从消息队列中读取消息,如果消息队列为空将会堵塞等待 if (msg == null) { // No message indicates that the message queue is quitting. returnfalse; }
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. finallongptr= mPtr; //mPtr是一个long类型,是native层c++类NativeMessageQueue对象的指针 if (ptr == 0) { returnnull; }
intpendingIdleHandlerCount= -1; // -1 only during first iteration intnextPollTimeoutMillis=0; for (;;) { if (nextPollTimeoutMillis != 0) { Binder.flushPendingCommands(); }
// Process the quit message now that all pending messages have been handled. if (mQuitting) { dispose(); returnnull; }
// 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. if (pendingIdleHandlerCount < 0 && (mMessages == null || now < mMessages.when)) { pendingIdleHandlerCount = mIdleHandlers.size(); } if (pendingIdleHandlerCount <= 0) { // No idle handlers to run. Loop and wait some more. mBlocked = true; continue; }
// Run the idle handlers. // We only ever reach this code block during the first iteration. for (inti=0; i < pendingIdleHandlerCount; i++) { finalIdleHandleridler= mPendingIdleHandlers[i]; mPendingIdleHandlers[i] = null; // release the reference to the handler
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; } }
structepoll_event eventItem; memset(& eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union eventItem.events = EPOLLIN; //设置eventfd为可读 eventItem.data.fd = mWakeEventFd.get(); //把eventfd文件描述符添加到epoll的监控列表中 int result = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mWakeEventFd.get(), &eventItem); ...... }
synchronized (this) { // Try to retrieve the next message. Return if found. finallongnow= SystemClock.uptimeMillis(); MessageprevMsg=null; Messagemsg= 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()); } ......