Handler機制

  handler是一個Android SDK 提供給開發者方便進行異步消息處理的類,下面從handler類最常用的函數sendMessage講起。sendMessage接受的參數是Message,調用到sendMessageDelayed,sendMessageDelayed的第二個參數delayMillis是0,表示立刻發送出去。如果需要延遲發送消息,使用參數delayMillis是不爲0的函數sendMessageDelayed即可。

/frameworks/base/core/java/android/os/Handler.java

    public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }
    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }
    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);
    }

  來插一段關於handler的構造函數和同步異步消息的內容,直接使用new handler()的話,會調用到下面這一段。其中callback參數爲null(當然也可以使用new handler(Callback)使callback參數不爲null,用法後面再介紹),async爲false,表示由該handler發出的消息同步的。一方面,可以修改handler的參數async爲true使得該handler發出的消息都是異步的;另一方面,可以通過Message類的setAsynchronous函數設置一個消息是異步的。後面將提到同步消息和異步消息的作用。

/frameworks/base/core/java/android/os/Handler.java

    public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            //handler需要定義成靜態內部類,否則會發生內存泄漏
            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());
            }
        }

        //Looper是一個線程專有的循環處理消息隊列的類
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        //每個Looper關聯一個MessageQueue,用來存儲消息Message
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

/frameworks/base/core/java/android/os/Handler.java

    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            //設置成異步消息
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

  enqueueMessage的when入參表示該消息應該被髮送出去的時間點。mMessages記錄了MessageQueue中第一個消息。實際上,所有的消息會組成一個按時間戳從早到晚排列單向鏈表,只是在插入元素時按時間戳來確定插入位置,處理消息的時候都是先對這個鏈表的第一個元素進行處理,因爲這個消息的時間戳是最早的,使得這個鏈表的性質類似於先進先出的隊列。
  needWake是用來喚醒阻塞在MessageQueue類的函數next的線程的。在兩種情況下,needWake爲true,表示需要喚醒阻塞線程:1.Looper無事可做的時候拿到了被認爲可以處理的消息。這個無事,是指沒有空閒處理元素IdleHandler且消息隊列沒有可以處理的消息或者消息隊列的消息還沒到發送時間的時候,這時候,有消息過來了,要麼消息隊列不爲空了,要麼新來的消息時間戳比消息隊列頭的還要早,這就需要看下是否真正進行處理了。2.隊列頭是一個barrier且新來的消息是時間戳最早的異步消息且Looper無事可做的時候。異步消息不會受到barrier的影響,但爲什麼要是最早的才喚醒呢?因爲這時候線程可能是出於等待時間到達或者阻塞狀態,只有直接更新消息隊列頭的操作才能叫醒它:“嘿,看看但新來的那個,時間符不符合你要求,符合要求就拿走吧。什麼?你沒消息處理了??那直接拿走吧!”。後面將提到barrier的概念。

/frameworks/base/core/java/android/os/MessageQueue.java

    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("MessageQueue", e.getMessage(), e);
                msg.recycle();
                return false;
            }

            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
            //消息隊列爲空或者時間戳爲0或者時間戳早於消息隊列第一個元素
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                //插入消息到隊列頭,使mMessages指向隊列頭
                msg.next = p;
                mMessages = msg;
                //後面會提到,mBlocked在Looper尚不能處理消息且空閒處理元素IdleHandler個數爲0的時候爲true
                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.
                //p.target == null的情況在調用enqueueSyncBarrier安插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; // invariant: p == prev.next
                prev.next = msg;
            }

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

  Looper堆消息隊列的處理如下:通過MessageQueue#next()取得要處理的消息,交給handler,進而調用dispatchMessage分派消息。重點看看MessageQueue#next()。

/frameworks/base/core/java/android/os/Looper.java

    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;

        // 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();
        }
    }

  nativePollOnce的第一個參數表示native層對應的MessageQueue指針,第二個參數表示等待時間,和epoll_wait的時間參數用法相同,0表示立刻返回,-1表示阻塞到有等待的事件發生,正數表示等待多長時間後返回。
Looper每次都是先對消息隊列的第一個元素進行處理。如果是一個barrier,將會跳過後面的所有同步消息(即isAsynchronous返回false的Message),直到遍歷完消息隊列或者拿到一個異步消息。當然,在沒有barrier的情況下,所有的同步消息和異步消息都是被同等地對待的。如果拿到了一個消息(可能是同步也可能是異步,取決於是否有barrier),如果當前時間還沒到發送時間,則將nextPollTimeoutMillis設置爲當前時間與發送時間的差值,下次調用nativePollOnce會等待這個差值的時間(前提是沒有空閒處理元素)。如果當前時間已經到達發送時間,則將這個消息從隊列中摘除返回。如果遍歷消息隊列沒有消息可用(可能是空隊列或者barrier後面全爲同步消息),則將nextPollTimeoutMillis設置成-1,下次調用nativePollOnce會阻塞到有等待的事件發生(前提是沒有空閒處理元素)。在消息隊列爲空或者頭消息時間戳還沒到達時,Looper會進行空閒事件處理。mIdleHandlers記錄了這些空閒處理元素。空閒事件處理就是對這些空閒處理元素分別調用其實現的queueIdle()。若mIdleHandlers爲空,重新執行循環,這時候可能會引發阻塞。若mIdleHandlers不爲空,分別處理完這些些空閒處理元素後,將nextPollTimeoutMillis恢復爲0,因爲處理空閒元素時可能有可用消息過來了,沒必要根據nextPollTimeoutMillis來阻塞線程,設置成0檢查有沒有可用消息過來了直接返回。

/frameworks/base/core/java/android/os/MessageQueue.java

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

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                //隊列頭爲barrier的情況。
                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) {
                        // 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.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (false) Log.v("MessageQueue", "Returning message: " + msg);
                        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.
                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;
                }

                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("MessageQueue", "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;
        }
    }

  由上面可以瞭解到,barrier是用來阻塞後面的同步消息的。安裝barrier是通過enqueueSyncBarrier進行的。mNextBarrierToken記錄了下一個可用的barrier編號。值得注意的是,通過Message.obtain()得到的Message關聯的handler爲null(即成員target爲null)。所以,在消息隊列中的消息target爲null的都可視作是barrier。barrier也是一個消息,也按照時間戳的先後順序放入到消息隊列中,但是它的存在會使後面的同步消息在MessageQueue#next()時被忽略。

/frameworks/base/core/java/android/os/MessageQueue.java

    int enqueueSyncBarrier(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;
        }
    }

  移除barrier的函數是removeSyncBarrier。若移除的barrier在消息隊列中間,直接移除即可。若移除的barrier在消息隊列頭部,mMessages設置爲barrier的下一個消息,若這時mMessages爲空或者mMessages不是barrier,則喚醒阻塞在MessageQueue#next()的線程,告訴線程沒事幹啦,可以執行下空閒處理了!或者告訴線程有活幹了,可以處理消息了。如果mMessages是barrier,則不需要喚醒線程,畢竟一個barrier和兩個連續的barrier的效果是相同的,等着新消息來再喚醒吧!
  barrier的一個主要用法是讓一個handler在一個時間段內只能處理異步消息。默認情況下,消息都是同步的,我們可以使用setAsynchronous將我們要處理的消息設置成異步。加入barrier後,就只能處理後面的異步消息了。當處理完異步消息後,使用removeSyncBarrier摘除這個barrier,又可以處理同步消息了。

/frameworks/base/core/java/android/os/MessageQueue.java

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

  接下來看看MessageQueue#next()怎麼阻塞在nativePollOnce的。Java層的Looper在native層也對應一個C++的Looper。接下來調用Looper::pollOnce。

/frameworks/base/core/jni/android_os_MessageQueue.cpp

static void android_os_MessageQueue_nativePollOnce(JNIEnv* env, jclass clazz,
        jlong ptr, jint timeoutMillis) {
    NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
    nativeMessageQueue->pollOnce(env, timeoutMillis);
}

void NativeMessageQueue::pollOnce(JNIEnv* env, int timeoutMillis) {
    mInCallback = true;
    mLooper->pollOnce(timeoutMillis);
    mInCallback = false;
    if (mExceptionObj) {
        env->Throw(mExceptionObj);
        env->DeleteLocalRef(mExceptionObj);
        mExceptionObj = NULL;
    }
}

  這裏插入一段關於Looper::addFd用法的介紹。addFd用於向Looper申請監聽來自文件描述符fd的events事件,ident是表示符,當ident爲POLL_CALLBACK(-2)時,表示監聽到事件是會回調callback參數的回調函數,data參數爲攜帶的額外數據。Request結構體是對上述信息的封裝。
  mRequests的mRequests記錄了這些Request的集合。當要監聽的fd已被包含在mRequests的時候,變成修改對應的Request的監聽事件;否則,添加新的Request到mRequests中。

/system/core/libutils/Looper.cpp

int Looper::addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data) {
#if DEBUG_CALLBACKS
    ALOGD("%p ~ addFd - fd=%d, ident=%d, events=0x%x, callback=%p, data=%p", this, fd, ident,
            events, callback.get(), data);
#endif

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

    int epollEvents = 0;
    if (events & EVENT_INPUT) epollEvents |= EPOLLIN;
    if (events & EVENT_OUTPUT) epollEvents |= EPOLLOUT;

    { // acquire lock
        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)); // zero out unused members of data field union
        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);
        }
    } // release lock
    return 1;
}

  在epoll_wait返回的時間數量eventCount大於0是,若時間發生的fd不是讀端管道(後面會提到),那就是添加進去的fd發生了監聽事件。於是生成一個Response,Response記錄了這個fd發生的時間和對應的Request,添加到mResponses中。mResponses保存了所有監聽請求和監聽結果(除了管道)的信息。
  當addFd的入參callback不爲空時,Request的ident被設置爲POLL_CALLBACK。在生成新的Response後,會檢查mResponses每一個Response對應的Request是否帶有callback。有的話,調用callback的handleEvent函數,然後清除這個callback。

/system/core/libutils/Looper.cpp

int Looper::pollInner(int timeoutMillis) {
...
    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 {
                ALOGW("Ignoring unexpected epoll events 0x%x on wake read pipe.", epollEvents);
            }
        } else {
            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;
                pushResponse(events, mRequests.valueAt(requestIndex));
            } else {
                ALOGW("Ignoring unexpected epoll events 0x%x on fd %d that is "
                        "no longer registered.", epollEvents, fd);
            }
        }
    }
    ...
        // Invoke all response callbacks.
    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;
#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
            ALOGD("%p ~ pollOnce - invoking fd event callback %p: fd=%d, events=0x%x, data=%p",
                    this, response.request.callback.get(), fd, events, data);
#endif
            int callbackResult = response.request.callback->handleEvent(fd, events, data);
            if (callbackResult == 0) {
                removeFd(fd);
            }
            // 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;
}

void Looper::pushResponse(int events, const Request& request) {
    Response response;
    response.events = events;
    response.request = request;
    mResponses.push(response);
}

  回頭看看Looper::pollOnce。如果有新生成的Response,則在while循環裏,會先將每一個新生成的Response的相關信息輸出到入參outFd,outEvents,outData中(在這些入參都不爲null的情況下)。如果沒有新生成的Response,則返回pollInner的結果。

/system/core/libutils/Looper.cpp

int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
    int result = 0;
    for (;;) {
        //每次進入一次for循環,mResponseIndex置爲0,mResponses爲pollInner生成的新的Response集合。
        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 DEBUG_POLL_AND_WAKE
                ALOGD("%p ~ pollOnce - returning signalled identifier %d: "
                        "fd=%d, events=0x%x, data=%p",
                        this, ident, fd, events, data);
#endif
                if (outFd != NULL) *outFd = fd;
                if (outEvents != NULL) *outEvents = events;
                if (outData != NULL) *outData = data;
                return ident;
            }
        }

        if (result != 0) {
#if DEBUG_POLL_AND_WAKE
            ALOGD("%p ~ pollOnce - returning result %d", this, result);
#endif
            if (outFd != NULL) *outFd = 0;
            if (outEvents != NULL) *outEvents = 0;
            if (outData != NULL) *outData = NULL;
            return result;
        }

        result = pollInner(timeoutMillis);
    }
}

  阻塞操作可能發生在epoll_wait中,阻塞的時間取決於Java傳下來的timeoutMillis參數。epoll監聽的文件描述符有管道讀端和通過addFd添加的fd,Java層的nativeWake就是通過往管道寫端寫入內容來喚醒阻塞在epoll_wait的線程的。

/system/core/libutils/Looper.cpp

    int result = POLL_WAKE;
    mResponses.clear();
    mResponseIndex = 0;

    // We are about to idle.
    mIdling = true;

    struct epoll_event eventItems[EPOLL_MAX_EVENTS];
    int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);

    // No longer idling.
    mIdling = false;

    // Acquire lock.
    mLock.lock();

    // Check for poll error.
    if (eventCount < 0) {
        if (errno == EINTR) {
            goto Done;
        }
        ALOGW("Poll failed with an unexpected error, errno=%d", errno);
        result = POLL_ERROR;
        goto Done;
    }

    // Check for poll timeout.
    if (eventCount == 0) {
#if DEBUG_POLL_AND_WAKE
        ALOGD("%p ~ pollOnce - timeout", this);
#endif
        result = POLL_TIMEOUT;
        goto Done;
    }

    // Handle all events.
#if DEBUG_POLL_AND_WAKE
    ALOGD("%p ~ pollOnce - handling events from %d fds", this, eventCount);
#endif

    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 {
                ALOGW("Ignoring unexpected epoll events 0x%x on wake read pipe.", epollEvents);
            }
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章