Android 一起来看看面试必问的消息机制

前言

谈到 Android 的消息机制,相信大家应该不陌生,在日常开发中不可避免要接触到这方面的内容,而且这也是面试中常被问到的内容,最近本着「Read the Fucking Source Code」的原则,每天花半个小时开始看源码,从 Android 消息机制开始。本文的内容借鉴了「Android 开发艺术探索」,在此强烈向大家推荐这本书,可以说是 Android 进阶必备,质量真的相当高。

一、Android 消息机制的概述


Android 消息机制的主要是指的是 Handler 的运行机制以及 Handler 所附带的 MessageQueue 和 Looper 的工作过程,这三者实际上是一个整体,只不过我们在开发过程中比较多地接触 Handler 而已。

Handler 的主要功能是将任务切换到某个指定的线程中去执行,那么 Android 为什么要提供这个功能呢?这是因为 Android 规定访问 UI 只能在主线程中进行,如果在子线程中访问 UI,那么程序就会抛出异常。

那为什么 Android 不允许子线程中访问 UI 呢?这是因为 Android 的 UI 控件并不是线程安全的,如果在多线程中并发访问可能会导致 UI 控件处于不可预期的状态,那还有一个问题,为什么系统不对 UI 控件的访问加上锁机制呢?缺点有两个:

  • 加上锁机制会让 UI 访问的逻辑变得复杂
  • 锁机制会降低 UI 访问的效率,因为锁机制会阻塞某些线程的执行

Handler 创建完毕后,这个时候其内部的 Looper 以及 MessageQueue 就可以和 Handler 一起协同工作了,然后通过 Handler 的 post() 方法将一个 Runnable 投递到 Handler 的内部的 Looper 中去处理,也可以通过 Handler 的 send() 方法发送一个消息,这个消息同样会在 Looper 中去处理。其实 post() 方法最终也是通过 send() 方法来完成的。

接下来谈下 send() 的工作过程。当 Handler 的 send() 方法被调用时,它会调用 MessageQueue 的 enqueueMessage() 方法将这个消息放入消息队列中,然后 Looper 发现有新消息到来时,就会处理这个消息,最终消息中的 Runnable 或 Handler 的 handleMessage() 就会被调用。注意 Looper 是运行在创建 Handler 所在的线程中去执行的,这样一来 Handler 中的业务逻辑就被切换到创建 Handler 所在的线程中去执行了。

Android 消息机制流程图.png

二、消息队列的工作原理


消息队列在 Anroid 中指的是 MessageQueue,MessageQueue 主要包含两个操作:插入和读取。读取操作本身会伴随着删除操作,插入和删除对应的方法分别为:enqueueMessage()next(),其中 enqueueMessage() 的作用是往消息队列中插入一条消息,而 next() 的作用是从消息队列中取出一条消息并将其从消息队列中移除。尽管 MessageQueue 叫做消息队列,但是它的内部实现并不是用的队列,实际上它是通过一个单链表的数据结构来维护消息队列的,因为单链表在插入和删除上比较有优势。

接下来看下它的 enqueueMessage()next() 方法的实现,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) {
                // 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;
    }

可以看到 enqueueMessage() 中,主要就是进行了单链表的插入操作。

接下来看看 next() 的源码:

    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.
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }

            nativePollOnce(ptr, nextPollTimeoutMillis);

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

                // Process the quit message now that all pending messages have been handled.
                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.
                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;
                }

                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.
            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.
            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.
            nextPollTimeoutMillis = 0;
        }
    }

可以看到 next() 方法是一个无限循环的方法,如果消息队列中没有消息,那么 next() 方法会一直阻塞在这里,当有新消息到来时,next() 方法会返回这条消息并将其从消息队列中删除。

三、Looper 的工作原理


Looper 在 Android 的消息机制中扮演着消息循环的角色,具体来说就是它会不停地从 MessageQueue 中查看是否有新的消息,如果有新消息就回立刻处理,否则就一直阻塞在那里。

先来看下它的构造方法:

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

在构造方法中,它会创造一个 MessageQueue 即消息队列,然后将当前的线程对象进行保存。

我们知道,Handler 的工作需要 Looper,没有 Looper 的线程就会报错,那么如何为一个线程创建 Looper 呢?其实很简单,通过 Looper.prepare() 就可以为当前线程创建一个 Looper,接着通过 Looper.loop() 来开启消息循环。

Looper 除了 prepare() 方法外,还提供了 prepareMainLooper() 方法,这个方法主要是给主线程创建 Looper 使用的,其本质也是通过 prepare() 方法来实现的。Looper 还提供了 quit()quitSafely() 两个方法来退出一个 Looper,两者的区别是:quit() 会直接退出 Looper,而 quitSafely() 只是设定一个退出标识,然后把消息队列中的消息处理完毕后才安全地退出。

    public void quitSafely() {
        mQueue.quit(true);
    }

Looper 最重要的一个方法是 loop() 方法,只有调用了 loop() 后,消息循环系统才会真正地起作用,Looper 的 loop() 方法的工作过程也比较好理解,loop() 方法是一个死循环,唯一跳出循环的方式是 MessageQueue 返回 null,当 Looper 的 quit() 被调用时,Looper 就会调用 MessageQueue 的 quit() 或者 quitSafely() 方法来通知消息队列退出,当前消息队列被标记为退出状态时,它的 next 方法就回返回 null。

四、Handler 的工作原理


Handler 的工作主要包括消息的发送和接收过程。消息的发送可以通过 post() 的一系列方法以及 send() 的一系列方法来实现,post() 的一系列方法最终也是通过 send() 的一系列方法来实现的。发送一条消息的典型过程如下所示。

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

可以发现,Handler 发送消息的过程仅仅是向消息队列中插入一条消息,MessageQueue 的 next() 方法就会返回这条消息给 Looper,Looper 收到消息就开始处理,最终消息由 Looper 交给 Handler 进行处理,即 dispatchMessage() 方法会被调用,这时 Handler 就进入了处理消息的阶段,dispatchMessage() 的具体实现如下所示:

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

Handler 处理消息的过程如下:

首先检查 Message 的 callback 是否为 null,不为 null,就通过 handleCallback() 来处理消息,Message 的 callback 是一个 Runnable 对象,实际上就是 Handler 的 post() 方法所传递的 Runnable 参数。handleCallback 的逻辑也比较简单,如下所示。

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

其次,检查 mCallback 是否为 null,不为 null 则调用 mCallback.handleMessage() 方法来处理消息。最后调用 Handler 的 handleMessage() 方法来处理消息。

总结


Android 的消息机制主要指 Handler 的运行机制,以及 Handler 所附带的 MessageQueue 和 Looper 的工作过程,三者是一个整体。当我们要将任务切换到某个指定的线程(如 UI 线程)中执行的时候,会通过 Handler 的 send(Message message msg)post(Runnable r) 进行消息的发送,post()方法最终也是通过 send() 方法来完成的。

发送的消息会插入到 MessageQueue 中(MessageQueue 虽然叫做消息队列,但是它的内部实现并不是队列,而是单链表,因为单链表在插入和删除上比较有优势),然后 Looper 通过 loop() 方法进行无限循环,判断 MessageQueue 是否有新的消息,有的话就立刻进行处理,否则就一直阻塞在那里,loop() 跳出无限循环的唯一条件是 MessageQueue 返回 null。

Looper 将处理后的消息交给 Handler 进行处理,然后 Handler 就进入了处理消息的阶段,此时便将任务切换到 Handler 所在的线程,我们的目的也就达到了。


猜你喜欢

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,924评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,902评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,716评论 0 239
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,783评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,166评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,510评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,784评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,476评论 0 196
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,196评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,459评论 2 243
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,978评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,321评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,964评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,046评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,803评论 0 193
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,530评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,420评论 2 265

推荐阅读更多精彩内容

  • 前言 Handler是Android消息机制的上层接口,平时使用起来很方便,我们可以通过它把一个任务切换到Hand...
    eagleRock阅读 1,622评论 0 13
  • 1. ANR异常 Application No Response:应用程序无响应。在主线程中,是不允许执行耗时的操...
    JackChen1024阅读 1,299评论 0 3
  • 引言 由于Android对消息机制的封装,开发者在平常的开发过程中,直接使用Handler对象就能满足大部分的应用...
    红灰李阅读 753评论 1 2
  • 本文出自 “阿敏其人” 简书博客,转载或引用请注明出处。 能简单说得我们尽量不复杂: 为了避免ANR,我们会通常把...
    阿敏其人阅读 33,667评论 5 109
  • 早上起来睁眼的时候,按掉了还没来得及歌唱的闹钟,舒展了一下身体打算起床,在掀开被子的刹那,突然想起来昨天跟同事做好...
    废材不废阅读 914评论 0 0