Android消息机制之Handler、MessageQueue、Looper源码分析

1、什么是Android消息机制?什么是Handler?为什么要用Handler?

Android消息机制主要是指Handler的运行机制,Handler运行需要底层的MessageQueue和Looper支撑。其中MessageQueue采用的是单链表的数据结构来存储消息列表,Looper可以理解为消息循环。由于MessageQueue只是一个消息存储单元,不能去处理消息,而Looper就是用来处理消息的,Looper会以无限循环的形式去MessageQueue中查找是否有新消息,如果有则取出消息并处理,否则就一直阻塞等待。Looper中还有一个特殊的概念是ThreadLocal,ThreadLocal的作用是可以在每个线程中存储数据,在Handler创建的时候会采用当前线程的Looper来构造消息循环系统,Handler内部就是通过ThreadLocal来获取每个线程的Looper,线程默认是没有Looper的,在使用Handler之前必须先为主线程创建Looper。大家可能有疑惑了,我们在代码中使用Handler的时候,并没有为主线程去创建Looper的代码,为什么也可以正常使用呢?那是因为主线程中ActivityThread被创建时已经初始化主线程的Looper。

Handler主要用于异步消息的处理:当发出一个消息(Message)之后,首先进入一个消息队列(MessageQueue),发送消息的函数(sendMessage())即刻返回,而另外一个部分在消息队列中逐一将消息取出,然后对消息进行处理,也就是发送消息和接收消息不是同步的处理。 这种机制通常用来处理相对耗时比较长的操作,比如从服务端拉取一些数据、下载图片等。

在Android中规定访问UI只能在主线程中进行(因为Android的UI控件不是线程安全的,如果在多线程中并发访问可能会导致UI控件处于不可预期的状态),如果在子线程访问UI,程序会抛出异常。如在子线程中拉取服务端数据之后需要更新UI上控件展示内容,这个时候就需要切换到主线程去操作UI,此时就可以通过Handler将操作UI的工作切换到主线程去完成。因此,系统之所以提供Handler,主要原因就是为了解决在子线程中无法访问UI的矛盾。

2、Handler简单使用

2.1、创建Handler实例的两种方式

2.1.1 通过Handler.Callback

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            return false;
        }
    });

2.1.2 通过派生Handler的子类

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

2.2、Handler发送消息常用的两种方式

2.2.1 sendMessage

Message message = new Message();
message.obj = "JokerWan";
message.what = 666;
// 发送消息
handler.sendMessage(message);
// 发送延迟消息
handler.sendMessageDelayed(message,3000);

2.2.2 post

handler.post(new Runnable() {
    @Override
    public void run() {
        // action           
    }
});     

3、Handler运行机制原理图

Android消息机制原理图.png

4、Handler运行机制源码分析

温馨提示:为了方便大家阅读,我这里贴出的代码会对源码进行删减,只保留部分跟本文相关的关键代码,其他代码用...代替

4.1、主线程Looper的创建

首先我们看到ActivityThread类中的main()方法的代码

    public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");

        ...

        Looper.prepareMainLooper();

        ...

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        ...
        
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

其中有两个关键代码Looper.prepareMainLooper();Looper.loop();,我们先看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();
        }
    }

继续跟进其中调用的prepare(false);方法

    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变量,找到它的声明

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

类型是ThreadLocal,泛型是Looper,ThreadLocal是一个线程内部的数据存储类,通过它可以在指定的线程存储数据,其他线程无法获取该线程数据。我们继续跟进下sThreadLocal.get()方法,ThreadLocal#get()

    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

调用getMap方法并传入当前线程t,返回保存当前线程中的数据ThreadLocal.ThreadLocalMap的对象mapThreadLocalMap类似于HashMap,只不过ThreadLocalMap仅仅是用来存储线程的ThreadLocal数据,首先通过getMap()获取当前线程的ThreadLocal数据的map,接着用ThreadLocal的对象作为key,取出当前线程的ThreadLocal数据的map中存储的result,由于前面sThreadLocal变量声明的时候约定的泛型是Looper,所以这里返回result对象就是Looper对象,继续回到prepare()方法,首先取出当前线程的Looper对象,校验下Looper对象的唯一性,然后new Looper(quitAllowed)并保存在ThreadLocal当前线程中的数据中。

接着跟进Looper的构造方法

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

在Looper的构造函数中创建了一个MessageQueue的对象,并保存在Looper的一个全局变量mQueue中,所以,每个Looper对象都绑定了一个MessageQueue对象。

4.2、Handler发送消息到MessageQueue

4.2.1 Handler构造器

    public Handler() {
        this(null, false);
    }
    public Handler(Callback callback, boolean async) {
        ...

        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

首先调用Looper.myLooper();方法获取Looper对象,并保存在mLooper变量中,看一下Looper#myLooper()

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

若获取的Looper对象为null,则抛出异常Can't create handler inside thread xxThread that has not called Looper.prepare(),因为上面我们已经分析过了,Looper对象的创建是在prepare()方法中。
从ThreadLocal中获取当前线程(主线程)的Looper对象,接着将Looper中的MessageQueue保存到mQueue中,并将callback赋值给mCallback,当我们通过匿名内部类创建Handler时callback为null。

4.2.2 Handler#sendMessage

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

可以看到不管是调用sendMessage还是sendMessageDelayed,还有后面会讲到的post(runnable),最终都会调用enqueueMessage方法,方法里面首先将Handler对象赋值给msg.target,后面会通过msg.target获取Handler对象去处理消息(后面会讲到),然后调用了mQueueenqueueMessage(msg, uptimeMillis)方法,
跟进MessageQueue#enqueueMessage()

    boolean enqueueMessage(Message msg, long when) {
        ...
        synchronized (this) {
            ...
            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {
                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;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }
            ...
        }
        return true;
    }

MessageQueue是一个消息队列,主要包含两个操作,插入和读取,插入就是上面这个方法enqueueMessage,读取是next方法,后面会讲到。尽管MessageQueue叫消息队列,但它内部实现并不是队列,而是用单链表的数据结构来维护消息列表,主要原因是单链表在插入和删除上效率比较高。从enqueueMessage方法的实现来看,它的主要操作就是单链表的插入操作,将传进来的msg插入到链表中,并将msg.next指向上一个传进来的Message。

4.2.3 Handler#post

查看post方法源码

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

发现原来post方法也是调用的sendMessageDelayed方法去send Message,只是把我们传进来的Runnable对象通过调用getPostMessage方法构造成一个Message

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

通过Message.obtain()获取一个Message,将Runnable对象赋值给m.callback,并返回Message,到这里我们就知道了,原来post(Runnable r)方法只是把r放进一个message中,并将message发送出去

4.3、Looper轮询MessageQueue并将消息发送给Handler处理

前面我们已经分析过,在ActivityThread类中的main()方法中会调用Looper.prepareMainLooper();Looper.loop();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;

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

            ...

            try {
                msg.target.dispatchMessage(msg);
                ...
            } finally {
                ...
            }
            ...
            msg.recycleUnchecked();
        }
    }

首先获取到Looper对象和Looper对象里面的MessageQueue,然后构造一个死循环,在循环里面通过调用MessageQueue的next()方法取出Message分发给Handler去处理消息,直到取出来的msg为null,则跳出循环。msg.targetenqueueMessage方法中赋值为发送此Message的Handler对象,这里取出Handler对象并调用其dispatchMessage(msg)去处理消息,而Handler的dispatchMessage(msg)是在创建Handler时所使用的Looper中执行的,这样就成功的将代码逻辑切换到了指定的线程去执行。来看一下MessageQueue的next()具体实现

Message next() {
        ...
        for (;;) {
            ...
            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                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;
                }

                ...
        }
    }

可以看到next是一个阻塞操作,开启一个死循环来取Message,当没有Message时,next方法就会一直阻塞在那里,这也导致Looper.loop()方法也一直阻塞。

4.4、Handler处理消息

Looper对象从MessageQueue中取到Message然后调用Handler的dispatchMessage(msg)去处理消息

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

首先检查msg的callback是否为null,不为null则调用handleCallback(msg)来处理消息,还记得上面我们分析的post(runnable)吗,这里从msg取出的callback就是调用Handler的post方法传入的Runnable对象,看下handleCallback(msg)代码实现

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

实现很简单,就是取出Runnable对象并调用其中的run方法。

dispatchMessage方法接着检查mCallback是否为null,不为null就调用其handleMessage(msg)方法,mCallback类型为Callback接口,上面我们讲过Handler创建的两种方式,第一种方式就是在Handler的构造器中通过匿名内部类传入一个实现了Handler.Callback接口的对象,并在构造器赋值给mCallback

dispatchMessage方法最后调用Handler的handleMessage(msg)方法来处理消息,就是上面我们讲到的Handler创建的第二种方式:派生一个Handler的子类并重写其handleMessage方法来处理消息。

5、主线程的消息循环

前面我们分析了ActivityThread类中的main()会创建Looper和MessageQueue,并将MessageQueue关联到Looper中,调用Looper的loop方法来开启主线程的消息循环,那么主线程的消息是怎么发送的呢?ActivityThread类内部定义了一个Handler的子类HActivityThread就是通过这个内部类H来和消息队列进行交互并处理消息。

ActivityThread通过 ApplicationThread 和 AMS 进行进程间通信, AMS以进程间通信的方式完成 ActivityThread 的请求后会回调 ApplicationThread 中的 Binder 方法,然后 ApplicationThread会向 H 发送消息,H 收到消息后会将 ApplicationThread中的逻辑切换到 ActivityThread 中去执行,即切换到主线程中取执行,这个过程就是主线程的消息循环模型。

6、总结

  1. Handler 的背后有 Looper、MessageQueue 支撑,Looper 负责消息分发, MessageQueue 负责消息管理;
  2. 在创建 Handler 之前一定需要先创建 Looper;
  3. Looper 有退出的功能,但是主线程的 Looper 不允许退出;
  4. 异步线程的 Looper 需要自己调用 Looper.myLooper().quit(); 退出;
  5. Runnable 被封装进了 Message,可以说是一个特殊的 Message;
  6. Handler.handleMessage() 所在的线程是 Looper.loop() 方法被调用的线程,也可
    以说成 Looper 所在的线程,并不是创建 Handler 的线程;
  7. 使用内部类的方式使用 Handler 可能会导致内存泄露,即便在 Activity.onDestroy
    里移除延时消息,必须要写成静态内部类;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 161,326评论 4 369
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,228评论 1 304
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,979评论 0 252
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,489评论 0 217
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,894评论 3 294
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,900评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,075评论 2 317
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,803评论 0 205
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,565评论 1 249
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,778评论 2 253
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,255评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,582评论 3 261
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,254评论 3 241
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,151评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,952评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,035评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,839评论 2 277

推荐阅读更多精彩内容