[聚合文章] Android Handler消息机制实现原理

消息系统 1900-01-01 19 阅读

一、消息机制流程简介

在应用启动的时候,会执行程序的入口函数main(),main()里面会创建一个Looper对象,然后通过这个Looper对象开启一个死循环,这个循环的工作是,不断的从消息队列MessageQueue里面取出消息即Message对象,并处理。然后看下面两个问题:
循环拿到一个消息之后,如何处理?
是通过在Looper的循环里调用Handler的dispatchMessage()方法去处理的,而dispatchMessage()方法里面会调用handleMessage()方法,handleMessage()就是平时使用Handler时重写的方法,所以最终如何处理消息由使用Handler的开发者决定。
MessageQueue里的消息从哪来?
使用Handler的开发者通过调用sendMessage()方法将消息加入到MessageQueue里面。

上面就是Android中消息机制的一个整体流程,也是 “Android中Handler,Looper,MessageQueue,Message有什么关系?” 的答案。通过上面的流程可以发现Handler在消息机制中的地位,是作为辅助类或者工具类存在的,用来供开发者使用。下面通过源码来解决这个流程中的一些疑问和常见问题。

二、消息机制的源码分析

首先main()方法位于ActivityThread.java类里面,这是一个隐藏类,源码位置:frameworks/base/core/java/android/app/ActivityThread.java

public static void main(String[] args) {    ......    Looper.prepareMainLooper();    ActivityThread thread = new ActivityThread();    thread.attach(false);    if (sMainThreadHandler == null) {        sMainThreadHandler = thread.getHandler();    }    Looper.loop();    throw new RuntimeException("Main thread loop unexpectedly exited");}

Looper的创建可以通过Looper.prepare()来完成,上面的代码中prepareMainLooper()是给主线程创建Looper使用的,本质也是调用的prepare()方法。创建Looper以后就可以调用Looper.loop()开启循环了。main方法很简单,不多说了,下面看看Looper被创建的时候做了什么,下面是Looper的prepare()方法和变量sThreadLocal:

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();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));}

很简单,new了一个Looper,并把new出来的Looper保存到ThreadLocal里面。ThreadLocal是什么?它是一个用来存储数据的类,类似HashMap、ArrayList等集合类。它的特点是可以在指定的线程中存储数据,然后取数据只能取到当前线程的数据,比如下面的代码:

ThreadLocal<Integer> mThreadLocal = new ThreadLocal<>();private void testMethod() {    mThreadLocal.set(0);    Log.d(TAG, "main  mThreadLocal=" + mThreadLocal.get());    new Thread("Thread1") {        @Override        public void run() {            mThreadLocal.set(1);            Log.d(TAG, "Thread1  mThreadLocal=" + mThreadLocal.get());        }    }.start();    new Thread("Thread2") {        @Override        public void run() {            mThreadLocal.set(2);            Log.d(TAG, "Thread1  mThreadLocal=" + mThreadLocal.get());        }    }.start();    Log.d(TAG, "main  mThreadLocal=" + mThreadLocal.get());}

输出的log是

main  mThreadLocal=0Thread1  mThreadLocal=1Thread2  mThreadLocal=2main  mThreadLocal=0

通过上面的例子可以清晰的看到ThreadLocal存取数据的特点,只能取到当前所在线程存的数据,如果所在线程没存数据,取出来的就是null。其实这个效果可以通过HashMap<Thread, Object>来实现,考虑线程安全的话使用ConcurrentMap<Thread, Object>,不过使用Map会有一些麻烦的事要处理,比如当一个线程结束的时候我们如何删除这个线程的对象副本呢?如果使用ThreadLocal就不用有这个担心了,ThreadLocal保证每个线程都保持对其线程局部变量副本的隐式引用,只要线程是活动的并且 ThreadLocal 实例是可访问的;在线程消失之后,其线程局部实例的所有副本都会被垃圾回收(除非存在对这些副本的其他引用)。更多ThreadLocal的讲解参考:Android线程管理之ThreadLocal理解及应用场景

好了回到正题,prepare()创建Looper的时候同时把创建的Looper存储到了ThreadLocal中,通过对ThreadLocal的介绍,获取Looper对象就很简单了,sThreadLocal.get()即可,源码提供了一个public的静态方法可以在主线程的任何地方获取这个主线程的Looper(注意一下方法名myLooper(),多个地方会用到):

public static @Nullable Looper myLooper() {    return sThreadLocal.get();}

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;    for (;;) {        Message msg = queue.next(); // might block        if (msg == null) {            // No message indicates that the message queue is quitting.            return;        }        try {            msg.target.dispatchMessage(msg);        } finally {            if (traceTag != 0) {                Trace.traceEnd(traceTag);            }        }        msg.recycleUnchecked();    }}

上面的代码,首先获取主线程的Looper对象,然后取得Looper中的消息队列final MessageQueue queue = me.mQueue;,然后下面是一个死循环,不断的从消息队列里取消息Message msg = queue.next();,可以看到取出的消息是一个Message对象,如果消息队列里没有消息,就会阻塞在这行代码,等到有消息来的时候会被唤醒。取到消息以后,通过msg.target.dispatchMessage(msg);来处理消息,msg.target 是一个Handler对象,所以这个时候就调用到我们重写的Hander的handleMessage()方法了。
msg.target 是在什么时候被赋值的呢?要找到这个答案很容易,msg.target是被封装在消息里面的,肯定要从发送消息那里开始找,看看Message是如何封装的。那么就从Handler的sendMessage(msg)方法开始,过程如下:

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);}private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {    msg.target = this;    if (mAsynchronous) {        msg.setAsynchronous(true);    }    return queue.enqueueMessage(msg, uptimeMillis);}

可以看到最后的enqueueMessage()方法中msg.target = this;,这里就把发送消息的handler封装到了消息中。同时可以看到,发送消息其实就是往MessageQueue里面插入了一条消息,然后Looper里面的循环就可以处理消息了。Handler里面的消息队列是怎么来的呢?从上面的代码可以看到enqueueMessage()里面的queue是从sendMessageAtTime传来的,也就是mQueue。然后看mQueue是在哪初始化的,看Handler的构造方法如下:

public Handler(Callback callback, boolean async) {    if (FIND_POTENTIAL_LEAKS) {        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());        }    }    mLooper = Looper.myLooper();    if (mLooper == null) {        throw new RuntimeException(            "Can't create handler inside thread that has not called Looper.prepare()");    }    mQueue = mLooper.mQueue;    mCallback = callback;    mAsynchronous = async;}

mQueue的初始化很简单,首先取得Handler所在线程的Looper,然后取出Looper中的mQueue。这也是Handler为什么必须在有Looper的线程中才能使用的原因,拿到mQueue就可以很容易的往Looper的消息队列里插入消息了(配合Looper的循环+阻塞就实现了发送接收消息的效果)。

以上就是主线程中消息机制的原理。

那么,在任何线程下使用handler的如下做法的原因、原理、内部流程等就非常清晰了:

new Thread() {    @Override    public void run() {        Looper.prepare();        Looper.loop();        Handler handler = new Handler();    }}.start();
  1. 首先Looper.prepare()创建Looper并初始化Looper持有的消息队列MessageQueue,创建好后将Looper保存到ThreadLocal中方便Handler直接获取。
  2. 然后Looper.loop()开启循环,从MessageQueue里面取消息并调用handler的 dispatchMessage(msg) 方法处理消息。如果MessageQueue里没有消息,循环就会阻塞进入休眠状态,等有消息的时候被唤醒处理消息。
  3. 再然后我们new Handler()的时候,Handler构造方法中获取Looper并且拿到Looper的MessageQueue对象。然后Handler内部就可以直接往MessageQueue里面插入消息了,插入消息即发送消息,这时候有消息了就会唤醒Looper循环去处理消息。处理消息就是调用dispatchMessage(msg) 方法,最终调用到我们重写的Handler的handleMessage()方法。


文章参考:

《Android开发艺术探索》
Android中为什么主线程不会因为Looper.loop()里的死循环卡死?
Android线程管理之ThreadLocal理解及应用场景

注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。