Android 源码解析Handler消息传递机制


一直想写一篇关于Android中很重要的Handler消息传递机制的讲解,无奈老哥拖延症的问题一直拖到现在才着手开始ㄟ(▔,▔)ㄏ,Handler机制大家肯定都使用过,也很简单,但一提起Handler机制的源码,对于初学者来说可能还会有些头疼(每个Android开发者都经历过的阶段),其实Handler机制的源码也很容易理解,那么本文就将在源码的角度分享一下我对Handler机制的理解。

一、简介


讲到android中的Handler的消息机制相信大家都不会陌生,android中经常使用Handler机制进行跨线程消息传递的(当然handler的用处还有很多博主不一一列举了),为什么要跨线程呢?相信大家都很清楚android的机制工作线程(子线程)不能有更新UI操作,而UI线程(主线程)不能执行耗时操作的(activity中超过5秒的时间未能响应下一个事件、BroadcastReceive超过10未响应),耗时操作只能执行在工作线程(子线程)中,否则会报ANR(Application Not Responding) ,一旦发生ANR,程序奔溃了。那么如何解决这个问题呢?Android为我们提供了Handler消息机制用来实现在线程中执行耗时操作后,当需要更新UI时通过Handler发送消息回主线程中去执行更新UI的操作。

二、Handler机制简图和重要类&方法介绍


那么Android的Handler消息机制是如何工作的呢?那么下面我们在源码的角度详细解析一下Android的Handler消息机制。下图为handler消息传递机制的简图:

这里写图片描述

简略介绍Android中Handler机制中几个比较重要的类及其方法:(后文讲解handler消息机制调用流程时,会详细介绍)

1、Handler类,主要方法:

1.1 内置Callback接口,接收消息

  public interface Callback {
        public boolean handleMessage(Message msg);
    }


1.2 实现很多sendMessage方法用于发送消息到messageQueue(这个大家常用(~ ̄▽ ̄)~,这里不多介绍)。
1.3 Handler.post()方法传入一个Runnable回调的run方法可以执行在主线程,通常用于一些更新UI操作。
1.4 dispatchMessage(Message msg)方法,当messsage出队列时调用分发消息。
其中这个handleCallback(msg);方法和Handler.post()、runUiThread()方法执行相关,下文会详细介绍。

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


2、Looper类,主要方法:

2.1 prepare()方法初始化Looper和MessageQueue,同时将初始化的Looper放入ThreadLocal中。

public static void prepare() {
        prepare(true);
    }
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));
}


2.2 构造函数私有化

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


2.3 loop()方法用于轮询MessageQueue。

2.4 quitSafely()方法终止轮询MessageQueue。

3、Message类,主要方法:

3.1 属性:what arg1 arg2 obj(常用不仔细介绍了),target(Handler):发送Message的handler对象引用,callback(Runnable):Handler.post()方法传入的Runnable对象。

3.2 obtain()方法返回Message实例从global pool中,避免你创建太多实例。

4、MessageQueue类,主要方法:

4.1 next()出队方法,返回队首Message

5、ThreadLocal类,主要方法:

5.1 set(T value)方法,存储数据,与当前线程绑定。
5.2 get()方法,根据调用线程返回存储数据,与 set(T value)方法对应。

三、Handler机制整体调用流程&源码分析

这里写图片描述

这么多准备工作后,那接下来进入正篇,我们就拿下面这段代码结合handler消息传递机制的简图,详细讲解一下Android中Handler机制:这是一个很清晰的示例代码,告诉我们创建Handler分三个步骤,我们索性称他为:Handler机制的三部曲:
1、Looper.prepare(),初始化Looper 、MessageQueue等等;
2、sendMessage发送消息到MessageQueue消息队列,实现handleMessage(Message msg)接收消息;
3、Looper.loop();开始轮询MessageQueue,拿到Message进行分发操作。

class LooperThread extends Thread {
  *      public Handler mHandler;
  *
  *      public void run() {
  *          Looper.prepare();
  *
  *          mHandler = new Handler() {
  *              public void handleMessage(Message msg) {
  *                  // process incoming messages here
  *              }
  *          };
  *
  *          Looper.loop();
  *      }
  *


看到上面代码可能有些老哥有点疑惑,平时自己在使用handler的时候也没有调用Looper.prepare()、Looper.loop()操作啊,比如我们在activity中直接初始化handler之后就可以发消息,收消息执行相关操作了啊?

针对这个疑问我们先给出结论,随着我们对源码的深入解析你会理解的更加透彻。你创建时没有调用Looper.prepare()、Looper.loop()依然可以使用而不报错,这里有一个前提条件是:你一定是在主线程中初始化的handler那你可能还会问为什么在主线程中初始化handler就不需要调用Looper.prepare()、Looper.loop()呢?答案是其实在主线程中程序启动时,已经帮你调用了Looper.prepare()、Looper.loop(),在ActivityThread中的main()方法中,我们可以找到相关代码如下:

    public static void main(String[] args) {

       .....//为了方便大家查看我删除了一下不相关代码

        Looper.prepareMainLooper();//这里开始调用Looper.prepare()
        ActivityThread thread = new ActivityThread();
        thread.attach(false);
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();//开始调用Looper.loop()

     ......//为了方便大家查看我删除了一下不相关代码
    }


可以看到在主线程中程序的main()方法中已经调用了这两个方法,所以你不需要再去自己调用。

好那么我们回来继续介绍这三部曲:

1、Looper.prepare()

上文handler机制简图中,我们已经简单介绍了一下Looper.prepare()作用,Looper.prepare()的主要作用就是做一些初始化操作,初始化Looper放入ThreadLocal中、初始化MessageQueue,我们看一下相关源码:
补充:关于ThreadLocal这个类,由于篇幅问题,我会单独开一篇博客去详细讲解.在本文中你只需知道Looper是存储在这个类中,这个类通常使用来存储一些以线程为作用域的数据,其内部是以线程为key,数据为value进行存储的,线程之间数据是隔离开的。ThreadLocal详细解析连接

 public static void prepare() {
        prepare(true);
    }
 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));
    }


我们可以看到当我们调用Looper暴露给我们的prepare()方法时,会在方法内部调用prepare(boolean quitAllowed)方法,sThreadLocal.get() != null检查ThreadLocal在当前线程下是否已经初始化过的Looper,如果有则会抛出异常"Only one Looper may be created per thread"这段代码实际就是为了限制一个Handler的looper只能被初始化一次,即一个handler只能对应一个Looper,在一个handler内部多次调用Looper.prepare()方法时会抛出这个异常)如果没有则new Looper(quitAllowed) 存储到ThreadLocal中,我们可以注意到new Looper时,参数传递一个布尔值True,那么这个参数有什么实际意义呢?我们来看一下Looper的构造方法:

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


我们可以看到Looper的构造方法被私有化了,所以我们只能通过Looper.prepare()去创建Looper对象,在构造方法中又初始化了MessageQueue同时传入了我们传递过来的布尔值,同时获取当前线程赋值给mThread,这次我们知道我们传递的参数使用来初始化MessageQueue使用了。那我们继续追踪:


// True if the message queue can be quit.
    private final boolean mQuitAllowed;

MessageQueue(boolean quitAllowed) {
        mQuitAllowed = quitAllowed;
        mPtr = nativeInit();
    }


在MessageQueue的构造方法我们看到了这个参数的赋值给了mQuitAllowed,通过注释我们终于清楚了,这个参数的实际作用,就是设置初始化的消息队列MessageQueue是否可以被终止,在MessageQueue中我们也可以找到对应终止消息队列的方法:

 void quit(boolean safe) {
        if (!mQuitAllowed) {
            throw new IllegalStateException("Main thread not allowed to quit.");
        }

        synchronized (this) {
            if (mQuitting) {
                return;
            }
            mQuitting = true;

            if (safe) {
                removeAllFutureMessagesLocked();
            } else {
                removeAllMessagesLocked();
            }

            // We can assume mPtr != 0 because mQuitting was previously false.
            nativeWake(mPtr);
        }
    }


我们可以看到当mQuitAllowed为true时可以终止当前的MessageQueue。那老哥们可能要问了,Looper.prepare()时都默认设置设置为true是不是所有的MessageQueue都可以被终止呢?答案是否定的,我们不要忘记主线程中的activityThread类中初始化的looper,prepareMainLooper()方法:

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


可以看到主线程初始化looper时传递的参数就是false,prepare(false)我们仔细思考一下自然也就能理解了,主线程的MessageQueue肯定是在整个application的生命周期内一直运行着的,直到程序退出才会被终止,所以初始化MessageQueue时设置不能被手动调用终止,也就很容易理解了,仔细观察上面quit方法的这段代码if(!mQuitAllowed) { throw new IllegalStateException("Main thread not allowed to quit.");也可以发现,当mQuitAllowed为false(即为主线程的MessageQueue)时,如果调用quit(boolean safe) 方法也会抛出异常提示Main thread not allowed to quit(主线程不被允许quit操作)

Looper.prepare()方法总结:

Looper.prepare()方法在初始化Handler前调用,用于初始化Looper、MessageQueue,由于Looper的构造函数私有化,所以为我们提供Looper.prepare()去创建一个Looper,同时在prepare()检查当前线程是否初始化过Looper,一个线程只能初始化一个looper,保证一个handler只能对应一个looper,通过调用ThreadLocal的set(T value)方法将初始化完成的Looper存储到ThreadLocal中进行线程隔离。主线程的MessageQueue不能调用quit方法终止,子线程可以调用quit方法终止消息队列。


2、sendMessage发送消息到MessageQueue消息队列

使用过handler的老哥肯定知道,实现handleMessage(Message msg)方法,用于接收消息执行相关操作,那消息是如何发送到handleMessage(Message msg)方法的呢?消息又是如何运转的呢?仔细看过本文开篇handler机制简图的老哥肯定对消息的传递有了一定认识。那么接下来我们就从源码的角度分析一下Message的运转。

我们有很多种发送消息的方法:

这里写图片描述


但是通过调用关系我们会发现他们最终几乎都会调用sendMessageAtTime(Message msg, long uptimeMillis)方法(sendMessageAtFrontOfQueue(Message msg)方法除外,这个方法后面我会单独给大家介绍)那我们就先看一下这个方法的源码:

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


方法参数1:msg 我们发送的消息对象
方法参数2:uptimeMillis=系统开机以来的毫秒数+延时毫秒数(未指定则为0)
观察源码我么会发现,首先进行的是消息队列MessageQueue初始化的检查,if (queue == null)直接抛出异常," sendMessageAtTime() called with no mQueue",MessageQueue如果已经初始化则会调用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);
    }


首先看一下这段代码msg.target = this;这段代码就是让发送的Message去持有发送此消息的handler的引用。主要是用于当消息出队时的消息分发操作(调用handler的dispatchMessage(Message msg)方法),下一部分解析Looper.loop();时你会更加清楚他的作用,mAsynchronous用于设定同步还是异步消息,创建handler时传递参数指定,默认是同步消息,这块想要理解同步消息和异步消息需要知道一个Barrier的概念,即拦截器。handler机制中拦截器的作用是当执行到这个拦截器消息时,后面的同步消息都暂时无法执行,异步消息可以正常执行,直到这个拦截器被移除

那么我们来看一下添加拦截器的代码:MessageQueue中的添加拦截器消息的一段代码postSyncBarrier()方法:

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


15-29行代码就是将一个拦截器消息添加到messageQueue中(这块是如何存储到messageQueue目前可能还不太好理解,没关系当看完后面MessageQueue中消息存储的结构你会很容易理解),仔细观察这个拦截器消息我们可以发现他和普通消息的不同就是:拦截器消息没有持有handler的引用,这点很重要,消息出队时,这一点将成为判断出队消息是否是拦截器消息的依据。

接下来我们看一下简单截取一小部分消息出队的代码如下:

                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 && msg.target == null)如果不持有handler的引用,即为一个拦截器消息时,prevMsg = msg; msg = msg.next;一直执行,不断检索消息队列,直到下一个消息为异步消息才退出while循环,执行异步消息。就是通过这种方式,实现拦截器的作用。只有同步消息才会被拦截器拦截。异步消息不会被拦截。

那么我们接着上面分析,这个方法queue.enqueueMessage(msg, uptimeMillis)就是实际的入队操作了,将handler发送的消息存入消息队列MessageQueue中,我们继续分析MessageQueue是如何存储的消息的:

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


通过观察源码(11-45行代码)我们可以看的很明白,首先消息队列MessageQueue并不是我们想的那样用一集合存储所有的消息,放到MessageQueue中,代替的是MessageQueue只存储当前需要处理的消息mMessages,每当有新消息msg入队时,总是和当前消息mMessages比较先执行哪一个消息,比较的规则就是根据我们传入的参数uptimeMillis,uptimeMillis越小越先执行,同时通过msg.next去指定下一需要执行的消息,整体结构和C语言中的链表很像,每个非末尾消息中都存储着下一个需要执行的消息。其结构如同一个链表如下图:
这里写图片描述

我看在看一下这一段代码if (p == null || when == 0 || when < p.when),p == null很好理解即当前队列中没有需要执行的Message,when < p.when也很好理解新入队的消息msg比当前队列中消息的uptimeMillis更小,需要优先执行,但是when == 0是一种什么情况呢?记住我们上面讲过这个 uptimeMillis=系统开机以来的毫秒数+延时毫秒数(未指定则为0)的,看似这个值是不能为0的啊,的确这个值确实理论上不可能为0,当我们似乎忘记我们还有一个特别的方法没有讲解,上文介绍消息发送方法时,我们说话几乎所有方法都是调用了sendMessageAtTime(Message msg, long uptimeMillis),但是有个方法除外,那就是sendMessageAtFrontOfQueue(Message msg)方法,那么现在我们就去分析一下这个特别的方法:

public final boolean sendMessageAtFrontOfQueue(Message msg) {
        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, 0);
    }


看到源码之后,一切都揭晓了,enqueueMessage(queue, msg, 0);就造就了when == 0,这种看似不可能的情况,他们没有通过sendMessageAtTime(Message msg, long uptimeMillis)方法入队,而是直接调用了入队方法enqueueMessage(queue, msg, 0),指定uptimeMillis=0,那么可能会有个疑惑,就是这样做到底为了什么呢?也很容易解答,这个方法就是让你可以发送一个消息让其在消息队列的队首,可以最先执行。因为他手动指定了uptimeMillis=0,是一个最小值,所以通过这个方法发送的消息会一直在消息队列MessageQueue的队首。

其实我们还会经常使用的一个方法就是Handler的post(Runnable r)方法传入一个Runnable,回调的run方法可以在主线程去执行,可做更新UI等操作。通过查看源码我们也可以发现其实他最终主要也是调用sendMessageAtTime(Message msg, long uptimeMillis)方法,只不过调用前先通过getPostMessage(Runnable r)方法将Runnable封装成一个Message(即将Runnable赋值给Message的callback属性),具体代码如下:

private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }

但需要注意的是postAtFrontOfQueue(Runnable r)是调用的sendMessageAtFrontOfQueue(Message msg)方法。

public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }


最终同样是调用sendMessageAtTime(Message msg, long uptimeMillis)方法实现消息入队。

同样的的方法还有一个就是activity类下的runUiThread()方法:

    public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }


简单易懂,如果当前线程不是主线程则调用的是handler的post方法,如果是主线程则直接调用run放法。具体为什么post方法的run方法就可以执行在主线程,将在下一部分Looper.loop()方法中给出的详细的讲解。


sendMessage发送消息到MessageQueue消息队列小结:

handler的sendMessage和post都是主要通过sendMessageAtTime(Message msg, long uptimeMillis)将消息发送到MessageQueue中,当然也有列外就是sendMessageAtFrontOfQueue(Message msg)(注意post方法中的postAtFrontOfQueue(Runnable r)其实最终也是调用的sendMessageAtFrontOfQueue(Message msg))方法直接将消息发送至MessageQueue中并指定其在队首,优先执行(他是通过直接指定uptimeMillis=0完成的)。MessageQueue的消息排序是通过uptimeMillis(uptimeMillis=系统开机以来的毫秒数+延时毫秒数(未指定则为0))排序的,uptimeMillis越小越先执行。同时MessageQueue并不是通过集合存储所有消息,而是只存储当前需要执行的消息,而每个消息去存储下一个需要执行的消息。类似一个链表结构。
如下图所示:

这里写图片描述


3、Looper.loop()

第二部分我们了解了当我们发送消息的时候,消息进入消息队列的过程以及消息队列中消息是如何存储和排序的,那么接下来我们就来讲解一下handler机制三部曲的最后一部分,轮询消息队列—-Looper.loop(),老样子我们先看源码:

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

            msg.recycleUnchecked();
        }
    }


通过观察loop()的源码(13行开始)我们可以发现loop()方法轮序消息队列是采用的方式是一个阻塞式的死循环for (;;),首先通过Message msg = queue.next();获取队列中的Message,然后在32行将取出来的消息通过msg.target.dispatchMessage(msg);方法进行分发,在第二部分我们讲过发送消息进入消息队列的时候,有这样的一行代码msg.target = this;就是让消息持有发送他的handler的引用,当时介绍我们说这行代码是为了消息出队后的分发操作,也就是调用msg.target.dispatchMessage(msg);进行消息分发的,好那么我们继续分析dispatchMessage(msg)方法的源码:

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


观察源码我们发现,首先dispatchMessage(Message msg)方法判断了消息中的msg.callback属性是否为null,是不是看着有点眼熟?好像前面的的某一部分见过,没错!在第二部分讲解handler的post()方法时,我们提到过post方法首先将传入的Runnable对象封装成Message对象,我们再看一下这个过程源码:

 private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }


这下清楚了吧,原来msg的这个callback属性就是我们post方法传过来的Runnable对象,那么这段if (msg.callback != null) { handleCallback(msg);}代码的含义也就很容易理解了,就是为了区分这个消息是通过post(Runnable r)系列还是通过sendMessage(Message msg)系列发送出去的,如果msg.callback != null证明是post发送出去的消息则执行handleCallback(msg);这个方法源码:

  private static void handleCallback(Message message) {
        message.callback.run();
    }


直接拿到这个callback(Runnable)对象执行它的run方法,所以这个run方法不确定执行在哪个线程。听到这里很多老哥可能有点疑惑,我们用的post方法的run回调不都是执行在主线程吗?怎么还不确定了?其实还是最初的情况,当你在主线程去初始化Handler时,系统在主线程中调用Looper.loop(),所以消息的分发操作即dispatchMessage(Message msg) 方法也在主线程中调用,自然handleCallback(Message message)方法也执行在主线程,所以直接调用run方法也会在主线程中回调。反之,如果在子线程中初始化handler子线程中调用Looper.loop()方法时,自然run回调就会在子线程中执行。

注*这里是直接调用Runnable的run方法,并不会新开辟个新线程。

我们继续分析dispatchMessage(Message msg)方法中的下面一部分代码:

if (mCallback != null) {
      if (mCallback.handleMessage(msg)) {
              return;
        }
   }
   handleMessage(msg);


很简单首先通过判断mCallback != null,决定用mCallback.handleMessage(msg)回调还是直接调用handleMessage(msg)方法,这个和你初始化handler选用的构造方法有关,也很好理解,具体查看handler的构造方法。Callback 接口如下:

   public interface Callback {
        public boolean handleMessage(Message msg);


Looper.loop()小结

handler机制中通过Looper.loop()方法采用阻塞是死循环的方式去轮询消息队列MessageQueue,取出消息,通过Handler的dispatchMessage(Message msg)方法进行分发,同时在分发操作时区分了是post方法还是sendMessage方法发送的消息,执行不同的处理,post消息直接通过handleCallback(msg);方法调用Runnable的run方法。sendMessage消息之直接分发给handleMessage(Message msg)去执行相关操作。注意:这里post方法的run回调的执行线程和Looper.loop()的执行线程一致


那么到这里,Handler消息机制的源码分析的分享也就大体完成了,写这篇文章的主要目的是希望对初次接触handler机制源码无从下手的老哥提供一些分享,希望能对大家有所帮助,同时也是自己学习Handler机制的一次记录。

如有疑问欢迎大家留言指正。祝大家生活愉快。

最后欢迎对Android开发感兴趣的老哥一起讨论。


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值