美文网首页
Handler源码解析

Handler源码解析

作者: i卓 | 来源:发表于2017-09-27 09:52 被阅读15次

    1.概述

    Handler一般在Android的UI线程和子线程间通信使用,之前我们在分析AsyncTask源码的时候就发现其实她的内部是Handler和Thread的一个组合,子线程做耗时的计算任务,Handler负责传递和接收结果。AsyncTask的源码解析请移步到我的另一篇文章AsyncTask源码分析

    2.用法

    我们这里简单回顾一下Handler的用法:

    创建一个Handler用来接收消息

    Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Bundle bundle = msg.getData();
                Logger.d(TAG,bundle.getString("Content"));
            }
    };
    

    发送消息

    Thread myThread  = new Thread(){
            @Override
            public void run() {
                super.run();
                Message message = handler.obtainMessage();
                message.what = 111;
                Bundle bundle = new Bundle();
                bundle.putString("Content","内容");
                message.setData(bundle);
                handler.sendMessage(message);
            }
        };
    

    3.源码相关解析

    消息机制一般有是三个主要组成部分:

    1.消息发送者;

    2.消息队列;

    3.消息处理循环

    运行机制:

    消息发送者通过某种方式,将消息发送到某个消息队列,同时存在一个消息处理循环,不断的从消息队列中取出消息进行处理。

    Android中的Handler消息处理主要由五个部分组成:
    Message:

    Message是线程中实实在在传递的消息,用于线程间交换数据,有四个常用字段,what、arg1、arg2、obj,前三者是int型,用于int型数据的传递,好处是轻量,obj可以传递稍复杂的object对象,但是请注意数据量不要太大;

    Handler:

    发送和处理消息,具体是怎么处理的待会儿再讲;

    MessageQueue

    消息队列,存放Handler发送过来的Message,它是一个单链表结构,消息会被一个接一个的处理,每个线程只存在一个消息队列

    Looper

    消息都存在MessageQueue中,怎么取出来呢?Looper中的loop()方法是一个死循环,Looper通过调用这个方法,只要消息队列中存在消息,就会一个接一个的取出来传递到Handler的handleMessage()中,当然的每个线程都只有一个一个Looper对象。

    ThreadLocal

    为了保证每个线程只有一个Looper对象,我们使用ThreadLocal来存储Looper,它的内部做了并发的相关处理,保证Looper的唯一性

    通过sendMessage()方法我们找到实际调用的是MessageQueue中的

    boolean enqueueMessage(Message msg, long when) {
            //msg.target是handler对象  
            if (msg.target == null) {
                throw new IllegalArgumentException("Message must have a target.");
            }
            //Message
            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) {
                    // New head, wake up the event queue if blocked.
                    msg.next = p;
                    mMessages = msg;
                    needWake = mBlocked;
                } else {
                    // 新消息会插入到链表的内部,一般情况下,这不需要调整唤醒时间。
                    // 但还必须考虑到当表头为“同步分割栏”的情况
                    needWake = mBlocked && p.target == null && msg.isAsynchronous();
                    Message prev;
                    for (;;) {
                        prev = p;
                        p = p.next;
                        if (p == null || when < p.when) {
                            break;
                        }
                        // 说明即便msg是异步的,也不是链表中第一个异步消息,所以没必要唤醒
                        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;
        }
    

    这段代码的意思是:在链表的合适位置插入Message节点。链表是按照时间排序的,这段代码主要是在比对Message的when信息,消息链表的第一个节点对应着最先被处理的消息,如果Message被插入到链表的头部,意味着队列的最近唤醒时间也跟着改变,needWake被置为true,进入nativeWake方法。nativeWake()方法对应的是c++层,我们暂不做深入研究。
    接下来我们看消息循环Looper的loop()方法。我们知道程序都有相应的入口,Activity是怎么样的消息驱动机制呢,在ActivityThread的main方法中我们发现是调用了 Looper.prepareMainLooper()创建主线程的Looper和MessageQueue,并通过 Looper.loop()开启消息循环。

    public static void prepareMainLooper() {
                prepare(false);
                synchronized (Looper.class) {
                    if (sMainLooper != null) {
                        throw new IllegalStateException("The main Looper has already been prepared.");
                    }
                    sMainLooper = myLooper();
                }
    }
    

    内部调用了prepare(false)和myLooper()

    private static void prepare(boolean quitAllowed) {
                if (sThreadLocal.get() != null) {
                    throw new RuntimeException("Only one Looper may be created per thread");
                }
                sThreadLocal.set(new Looper(quitAllowed));
    }
    

    sThreadLocal保存了一个Looper对象,首先判断是否已经存在Looper对象,ThreadLocal是并发安全的,同时保证么个线程只有一个Looper对象。
    我么看一下Looper的构造函数

    private Looper(boolean quitAllowed) {
            mQueue = new MessageQueue(quitAllowed);
            mThread = Thread.currentThread();
    }
    

    创建Looper的同时创建了一个MessageQueue消息队列和保存了当前线程,quitAllowed表示消息队列是否可以退出。

    prepareMainLooper()中调用的myLooper()是什么呢?看源码启示是从sThreadLocal中取出Looper。

    Looper的初始化完成了,接下来是另一个重要的方法Looper.loop():

    public static void loop() {
            final Looper me = myLooper();
            ...
            final MessageQueue queue = me.mQueue;
    
            Binder.clearCallingIdentity();
            final long ident = Binder.clearCallingIdentity();
    
            for (;;) {
                Message msg = queue.next();
                if (msg == null) {
                    return;
                }
                ...
                msg.target.dispatchMessage(msg);
                ...
                msg.recycleUnchecked();
            }
        }
    

    逻辑比较简单,通过一个死循环不断的从MessageQueue的next()方法中取出消息,然后调用msg.target.dispatchMessage(msg),再然后回收该消息,如果消息为空,继续循环,直到有新消息为止,这是一个阻塞操作,msg.target上文我们讲过就是handler对象。

    public void dispatchMessage(Message msg) {
            if (msg.callback != null) {
                handleCallback(msg);
            } else {
                if (mCallback != null) {
                   if (mCallback.handleMessage(msg)) {
                         return;
                     }
                }
                handleMessage(msg);
            }
    }
    

    msg.callback是什么呢,点击查看到Handler的构造函数我们看到callback是作为参数传入的,我们在调用Handler的post方法的时候传的是Runnable对象。

    我们来看看我们经常会用到的两个方法runOnUiThread和View的postDelayed

    public final void runOnUiThread(Runnable action) {
                if (Thread.currentThread() != mUiThread) {
                    mHandler.post(action);
                } else {
                    action.run();
                }
    }
    
    public boolean postDelayed(Runnable action, long delayMillis) {
                final AttachInfo attachInfo = mAttachInfo;
                if (attachInfo != null) {
                    return attachInfo.mHandler.postDelayed(action, delayMillis);
                }
                ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
                return true;
    }
    

    可以看到都是执行了主线程的run()方法。

    讲到这里Handler的通讯原理基本上讲完了,但是其实还有一个很重要的地方没有说到,就是MessageQueue的next()方法。MessageQueue是怎么一个接一个的取消息呢,我们来看:
    对消息队列而言,在摘取消息时还要考虑更多技术细节。

    消息队列它应该具有以下特点:

    1.当消息队列中没有新消息时,我们应该使之阻塞,而不应该继续下面的一系列的操作;

    2.队列里的消息应该按照时间先后顺序排列,最先到时的消息会放在队列的头部,时间这里指的是mMessage.when,依次排序;

    3.阻塞时间最好能精确,如果暂时没有合适的消息可以摘取时,要考虑链表的消息首个节点将什么时间到,这个消息节点到当前的时间差,就是我们要阻塞的时间;

    4.有些时候我们可能希望在消息队列进入阻塞的时候做一些动作,这些动作称为idle动作,我们需要兼顾处理这些idle动作。

    MessageQueue的next()函数如下:

    Message next() 
    {
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        
        for (;;) {
            . . . . . .
            nativePollOnce(mPtr, nextPollTimeoutMillis);    // 阻塞于此
            . . . . . .
                // 获取next消息,如能得到就返回之。
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;  // 先尝试拿消息队列里当前第一个消息
                
                if (msg != null && msg.target == null) {
                    // 如果从队列里拿到的msg是个“同步分割栏”,那么就寻找其后第一个“异步消息”
                    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);
                        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 (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;
                }
            . . . . . .
            // 处理idle handlers部分
            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);
                    }
                }
            }
            
            pendingIdleHandlerCount = 0;
            nextPollTimeoutMillis = 0;
        }
    }
    

    当MessageQueue的定时机制触发后,会判断这条消息是否真的到时,如果到时,则直接返回这个Message,如果没有到时,则计算一个等待时间,继续for循环继续调用nativePollOnce(mPtr, nextPollTimeoutMillis),进入阻塞状态,等待指定的等待时间。

    next()中的Idle Handler,我们前面说过,在消息队列阻塞之前,我们可能希望做一些其它的操作,比如垃圾回收,在ActivityThread中我们看一下GcIdler的定义:

    final class GcIdler implements MessageQueue.IdleHandler {
        @Override
        public final boolean queueIdle() {
            doGcIfNeeded();
            return false;
        }
    }
    

    Handler的消息机制我们讲完了,还有一些细节我们没有涉及,比如我们发现源码里面调用了native层的方法、比如同步分隔栏的原理,如果你想继续深入的研究下去,你可以去深究这些代码,下面的参考博文,讲的很详细,其实我也是查看源码,然后有一些不懂的地方去对照着这篇博文去理解,这里感谢这篇文章的博主。

    参考:

    聊一聊Android的消息机制

    相关文章

      网友评论

          本文标题:Handler源码解析

          本文链接:https://www.haomeiwen.com/subject/hovyextx.html