移步Android Handler机制详解

1 消息的取出主要是通过Looper的loop方法

代码如下Looper.java 122行

/**     * Run the message queue in this thread. Be sure to call     * {@link #quit()} to end the loop.     */    public static void loop() {         //第1步        final Looper me = myLooper();        if (me == null) {            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");        }        //第2步        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();         //第3步        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            final Printer logging = me.mLogging;            if (logging != null) {                logging.println(">>>>> Dispatching to " + msg.target + " " +                        msg.callback + ": " + msg.what);            }            final long traceTag = me.mTraceTag;            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));            }            try {                // 第5步                msg.target.dispatchMessage(msg);            } finally {                if (traceTag != 0) {                    Trace.traceEnd(traceTag);                }            }            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);            }            // 第6步            msg.recycleUnchecked();        }    }

方法已经在Android Handler机制2--Looper中说过了,我就重点说下流程,大体上分为6步

  • 第1步 获取Looper对象
  • 第2步 获取MessageQueue消息队列对象
  • 第3步 while()死循环遍历
  • 第4步 通过queue.next()来从MessageQueue的消息队列中获取一个Message msg对象
  • 第5步 通过msg.target. dispatchMessage(msg)来处理消息
  • 第6步 通过msg.recycleUnchecked()方来回收Message到消息对象池中

1.2 Message next()方法

代码在MessageQueue.java
307行

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.        // 如果消息循环已经退出了。则直接在这里return。因为调用disposed()方法后mPtr=0        final long ptr = mPtr;        if (ptr == 0) {            return null;        }        //记录空闲时处理的IdlerHandler的数量        int pendingIdleHandlerCount = -1; // -1 only during first iteration        // native层用到的变量 ,如果消息尚未到达处理时间,则表示为距离该消息处理事件的总时长,        // 表明Native Looper只需要block到消息需要处理的时间就行了。 所以nextPollTimeoutMillis>0表示还有消息待处理        int nextPollTimeoutMillis = 0;        for (;;) {            if (nextPollTimeoutMillis != 0) {                //刷新下Binder命令,一般在阻塞前调用                Binder.flushPendingCommands();            }            // 调用native层进行消息标示,nextPollTimeoutMillis 为0立即返回,为-1则阻塞等待。            nativePollOnce(ptr, nextPollTimeoutMillis);            //加上同步锁            synchronized (this) {                // Try to retrieve the next message.  Return if found.                // 获取开机到现在的时间                final long now = SystemClock.uptimeMillis();                Message prevMsg = null;                // 获取MessageQueue的链表表头的第一个元素                Message msg = mMessages;                 // 判断Message是否是障栅,如果是则执行循环,拦截所有同步消息,直到取到第一个异步消息为止                if (msg != null && msg.target == null) {                     // 如果能进入这个if,则表面MessageQueue的第一个元素就是障栅(barrier)                    // Stalled by a barrier.  Find the next asynchronous message in the queue.                    // 循环遍历出第一个异步消息,这段代码可以看出障栅会拦截所有同步消息                    do {                        prevMsg = msg;                        msg = msg.next;                       //如果msg==null或者msg是异步消息则退出循环,msg==null则意味着已经循环结束                    } while (msg != null && !msg.isAsynchronous());                }                 // 判断是否有可执行的Message                if (msg != null) {                      // 判断该Mesage是否到了被执行的时间。                    if (now < msg.when) {                        // Next message is not ready.  Set a timeout to wake up when it is ready.                        // 当Message还没有到被执行时间的时候,记录下一次要执行的Message的时间点                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);                    } else {                        // Message的被执行时间已到                        // Got a message.                        // 从队列中取出该Message,并重新构建原来队列的链接                        // 刺客说明说有消息,所以不能阻塞                        mBlocked = false;                        // 如果还有上一个元素                        if (prevMsg != null) {                            //上一个元素的next(越过自己)直接指向下一个元素                            prevMsg.next = msg.next;                        } else {                           //如果没有上一个元素,则说明是消息队列中的头元素,直接让第二个元素变成头元素                            mMessages = msg.next;                        }                        // 因为要取出msg,所以msg的next不能指向链表的任何元素,所以next要置为null                        msg.next = null;                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);                        // 标记该Message为正处于使用状态,然后返回Message                        msg.markInUse();                        return msg;                    }                } else {                    // No more messages.                    // 没有任何可执行的Message,重置时间                    nextPollTimeoutMillis = -1;                }                // Process the quit message now that all pending messages have been handled.                // 关闭消息队列,返回null,通知Looper停止循环                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.                // 当第一次循环的时候才会在空闲的时候去执行IdleHandler,从代码可以看出所谓的空闲状态                // 指的就是当队列中没有任何可执行的Message,这里的可执行有两要求,                // 即该Message不会被障栅拦截,且Message.when到达了执行时间点                if (pendingIdleHandlerCount < 0                        && (mMessages == null || now < mMessages.when)) {                    pendingIdleHandlerCount = mIdleHandlers.size();                }                                // 这里是消息队列阻塞( 死循环) 的重点,消息队列在阻塞的标示是消息队列中没有任何消息,                // 并且所有的 IdleHandler 都已经执行过一次了                if (pendingIdleHandlerCount <= 0) {                    // No idle handlers to run.  Loop and wait some more.                    mBlocked = true;                    continue;                }                    // 初始化要被执行的IdleHandler,最少4个                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.            // 开始循环执行所有的IdleHandler,并且根据返回值判断是否保留IdleHandler            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.            // 重点代码,IdleHandler只会在消息队列阻塞之前执行一次,执行之后改标示设置为0,            // 之后就不会再执行,一直到下一次调用MessageQueue.next() 方法。            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.            // 当执行了IdleHandler 的 处理之后,会消耗一段时间,这时候消息队列里的可能有消息已经到达              // 可执行时间,所以重置该变量回去重新检查消息队列。            nextPollTimeoutMillis = 0;        }    }

从MessageQueue中获取一个Message的时候,会分为以下几步

  • 首先、MessageQueue会先判断队列中是否有障栅的存在,如果有的话,只会返回异步消息,否则就逐个返回。
  • 其次、当MessageQueue没有任何消息可以处理的时候,它会进度阻塞状态等待新的消息到来(无线循环),在阻塞之前它会执行以便 IdleHandler,所谓的阻塞其实就是不断的循环查看是否有新的消息进入队列中。
  • 再次、当MessageQueue被关闭的时候,其成员变量mQuitting会被标记为true,然后在Looper视图从队列中取出Message的时候返回null,而Message==null就是告诉Looper消息队列已经关闭,应该停止循环了,这一点可以在Looper.loop()房源中看出。
  • 最后、如果大家细心一定会发现,Handler线程里面实际上有两个无线循环体,Looper循环体和MessageQueue循环体,真正阻塞的地方是MessageQueue的next()方法里

这里有个难点,我简单说下

//****************  第一部分  ***************                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 (DEBUG) Log.v(TAG, "Returning message: " + msg);                        msg.markInUse();                        return msg;                    }                } else {                    // No more messages.                    nextPollTimeoutMillis = -1;                }

MessageQueue的next方法也是一个循环,主要目的是获取下一个要被处理的Message,其中的几个要点:

  1. nativePollOnce是阻塞的,中间执行了epoll_wait等待,通过nativeWake主动唤醒或者到达超时时间后唤醒。
  2. 如果插入了SyncBarrier消息(handler为null的消息),则只会处理“异步”的消息(设置了Asynchronous flag的消息,详看后文)
  3. 如果当前消息没有到达when设定的时间,则会重新进入nativePollOnce,设置具体的超时时间
  4. 到达设定时间的Message会被返回,由Looper分发处理。
  5. 如果进入next()时没有消息要被马上处理,则会执行IdleHandler的处理。


    20170612160907505.jpg

nativePollOnce
nativePollOnce名字上理解应该是轮询一次的意思,代码如下:
android_os_MessageQueue.cpp在nativePollOnce方法中,调用了Looper的pollOnce方法:

/frameworks/base/core/jni/android_os_MessageQueue.cppstatic void android_os_MessageQueue_nativePollOnce(JNIEnv* env, jobject obj,        jlong ptr, jint timeoutMillis) {    NativeMessageQueue* nativeMessageQueue = reinterpret_cast(ptr);    nativeMessageQueue->pollOnce(env, obj, timeoutMillis);}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;    }}

它调用的pollInner函数中执行了epoll_wait,等待mWakeEventFd和其他注册的fd被唤醒,然后分发Native消息,等到函数返回后,Java层的MessageQueue.next()才继续执行。

/system/core/libutils/Looper.cppint Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {    ...    result = pollInner(timeoutMillis);}int Looper::pollInner(int timeoutMillis) {    //调整timeout时间    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;        }    }    ...    //epoll_wait,等待唤醒或超时    struct epoll_event eventItems[EPOLL_MAX_EVENTS];    int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);    ...    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) {                //清空mWakeEventFd管道                awoken();            } else {                ALOGW("Ignoring unexpected epoll events 0x%x on wake event fd.", epollEvents);            }        } else {            ...        }    }Done: ;    //Native层消息的分发    ...    return result;}//清空mWakeEventFd管道void Looper::awoken() {    uint64_t counter;    TEMP_FAILURE_RETRY(read(mWakeEventFd, &counter, sizeof(uint64_t)));}

那么唤醒这个epoll_wait的地方在哪?
nativeWake
android_os_MessageQueue.cpp的nativeWake函数,调用了Looper.cpp的wake()函数,向mWakeEventFd管道写入了数据,epoll_wait被唤醒。

Looper.cppvoid Looper::wake() {    uint64_t inc = 1;    //向mWakeEventFd管道写入数据    ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd, &inc, sizeof(uint64_t)));    ...}

那么问题又来了,何时去唤醒这个epoll? 答案在java层插入新消息时,调用的
MessageQueue.enqueueMessage()。

2 分发 msg.target.dispatchMessage(msg);方法

代码在Handler.java 93行

/**     * Handle system messages here.     */    public void dispatchMessage(Message msg) {        if (msg.callback != null) {            //当Message存在回调方法,回调msg.callback.run()方法;            handleCallback(msg);        } else {            if (mCallback != null) {                //当Handler存在Callback成员变量时,回调方法handleMessage();                if (mCallback.handleMessage(msg)) {                    return;                }            }            //Handler自身的回调方法handleMessage()            handleMessage(msg);        }    }

这个方法很简单就是二个条件,三种情况

  • 情况1:如果msg.callback 不为空,则执行handleCallback(Message),而handleCallback(Message)的内部最终调用的是message.callback.run();,所以最终是msg.callback.run()。
  • 情况2:如果msg.callback 为空,且mCallback不为空,则执行mCallback.handleMessage(msg)。
  • 情况3:如果msg.callback 为空,且mCallback也为空,则执行handleMessage()方法

分发消息时三个方法的优先级分别如下:

  • Message的回调方法优先级最高,即message.callback.run();
  • Handler的回调方法优先级次之,即Handler.mCallback.handleMessage(msg);
  • Handler的默认方法优先级最低,即Handler.handleMessage(msg)。

参考

Android Handler机制8之消息的取出与消息的其他操作
Handler机制及原理探究

更多相关文章

  1. 关于Android(安卓)O 通知渠道总结
  2. android xml解析 XmlPullParser的使用
  3. 13-6-3 android 自定义tabhost在底部与框架函数的讲解2
  4. Android(安卓)native 内存泄露检测
  5. Android(安卓)-- Context
  6. Android遇到的问题解决方法
  7. android 多线程实现方式、并发与同步学习总结
  8. SQlite数据库(4)---DAO(data access object)数据访问对象
  9. webView中js调用android方法一调用程序就退出是怎么回事

随机推荐

  1. Android onTouch事件解析
  2. Edittext在xml文件中设置android:focusabl
  3. iOS与Android的对比
  4. Android中Failed to 。。。。。。timeout
  5. 【经验记录】Android上传文件到服务器
  6. Android:Deprecated Thread methods are
  7. Android之四大组件解析
  8. 开源项目之Android DataFramework(数据库
  9. Android NDK开发学习(三)
  10. android ImageView实现圆角(xml实现方法)