Android消息传递机制

2017-04-16  本文已影响160人  Coralline_xss

Android消息传递机制

一、概述

    Android消息机制主要是指 Handler 的运行机制以及 Handler 所附带的 MessageQueue 和 Looper 的工作过程。

    在具体谈论这三者之间关系之前,先来了解一下什么叫异步消息处理线程。
    异步消息处理线程启动后会进入一个无线的循环体之中,每循环一次,从其内部的消息队列中取出一个消息,然后回调相应的消息处理方法,执行完成后继续循环。当消息队列为空是,线程就会被阻塞等待。
    这里无限循环和取消息是通过 Looper 来实现,消息队列指的就是MessageQueue,实为单链表,用来存放消息Message,Handler便是用来处理消息的。
    Looper是一个特殊的概念,将一个普通线程变成一部消息处理线程就必须使其拥有 Looper,若需要使用 Handler 就必须为线程创建 Looper 。例如常用的主线程,也即UI线程,对应 ActivityThread,在其 main() 方法中创建时就会初始化 Looper,这也是在主线程中能使用 Handler 的原因。(详情可查看源码:ActivityThread.main())

    下面先展示一段创建异步消息处理线程的代码:

Class LooperThread extends Thread {
    private MyHandler mHandler;
    class MyHandler extends Handler {
        public MyHandler(String name) {
            super(name);
        }
        
        @override
        public void handleMessage(Message msg) {
            // 处理消息
        }
    }
    
    @override
    public void run() {
        Looper.prepare();
    
        // do some initialization
        mHandler = new MyHandler();
        
        Looper.loop(); // 循环取消息
    }
}

    接下来先介绍一下 Looper、MessageQueue 以及 Handler 的工作原理,对上述有疑问的,可继续查看以下内容。

二、Looper 的工作原理

    Looper 在 Android 的消息机制中扮演着消息循环的角色,具体来说就是一直不停地从 MessageQueue 中查看是否有新的消息,若有就立即取出处理,没有就会阻塞直到有新的消息。以下主要介绍的Looper 的 prepare()、构造和 loop() 方法。

1、 Looper.prepare() 方法

    源码如下:

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() 方法,就会抛异常,说明一个线程只会创建一次Looper;如果不存在,就创建一个 Looper 对象,并存放到 sThreadLocal 中。

Note:
    简单介绍一下 sThreadLocal 这个 ThreadLocal 成员变量。
    ThreadLocal是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储后,只有在指定的线程中可以获取到存储的数据,对于其他线程就无法获取到数据,也即 Looper 的作用域是以线程为作用域并且不同的线程拥有不同的 Looper,可通过 ThreadLocal 实现 Looper 在不同线程中的存取。这里要记住一个线程只对应一个 Looper对象,如果在主线程中创建,就属于主线程,在子线程中创建就属于子线程。* *

2、 Looper构造方法

    源码如下:

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

    在构造方法会创建一个 MessageQueue,也即消息队列,然后将当前的线程保存起来,也即保存创建 Looper 的线程。

3、 Looper.loop() 方法

    主要代码如下:

public static void loop() {
    // 从 sThreadLocal 中取出 Looper 对象
    final Looper me = myLooper();
    // 为空,代码当前线程没有主动调用 prepare() 方法
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    // 取出 Looper对应的 MessageQueue消息队列
    final MessageQueue queue = me.mQueue;
    // 开始执行无限循环
    for (;;) {
        // 从队列中取出一个Message 消息,next()在队列中没有消息时会阻塞操作
        Message msg = queue.next(); // might block
        // 这里当取出的消息为空时,是跳出循环的唯一条件
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }
        final long traceTag = me.mTraceTag;
        if (traceTag != 0) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }
        try {
            // msg.targert为Handler对象,最初由 Handler.sendMessage()发送的消息,最终交由Handler 处理
            msg.target.dispatchMessage(msg);
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }

        msg.recycleUnchecked();
    }
}

Q:loop() 退出循环的唯一条件是从消息队列中取出的消息为 null,那么何时才会为 null 呢?
A:虽然 mQueue.next() 是一个阻塞方法,当队列中没有消息时,会一直阻塞,当主动调用 Looper.quit() 和 quitSafely(boolean) 方法时,就会调用 MessageQueue.quit() 方法,通知消息队列退出,当消息队列被标记为退出状态时,它的 next() 方法就会返回 null。
Q:msg.target.dispatchMessage() 实际上是交给 Handler 处理,那么怎样交由对应的线程来处理呢?这个问题等到 Handler 工作原理时来解答。

二、Handler 的工作原理

    Handler 的主要工作包括消息的发送和接收。消息的发送可以通过 post 的一系列方法以及 send 的一系列方法,不过最终都是通过 send 来实现的。

1、Handler.sendMessage() 方法

    我们经常会使用这样的方式发送一条消息:

Message msg = new Message();
msg.what = 0x11;
msg.obj = "Hello, world !";
handler.sendMessage(msg);

    查看 sendMessage() 方法源码可知,所有的 send() 和 post() 最终都会调用 handler.enqueueMessage(mQueue, msg, updateMillis) 方法,继续查看该方法源码如下:

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    // 设置 Message的 target成员变量为 Handler.this,将 Handler 和该 Message 绑定在一起
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    // 调用 MessageQueue 的进队方法
    return queue.enqueueMessage(msg, uptimeMillis);
}

    从上可知,Handler 发送消息的过程仅仅是向消息队列中插入一条消息,MessageQueue的 next() 方法就会返回这条消息给 Looper,Looper 收到消息就开始处理,最终消息由 Looper 交由 Handler 处理,也即 <code>msg.target = handler.dispatchMessage() </code>方法被调用,这是消息就进入处理阶段。

2、Handler.dispatchMessage() 方法

    消息处理方法dispatchMessage() 对应源码如下:

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

    处理过程如下:
(1)首先,检查 Message 的 callback 是否为 null,不为 null,就调用 handleCallback(msg) 方法处理消息。

(2)其次,检查 mCallback 接口是否为 null,不为 null,就回调 mCallback.handleMessage() 方法。

(3)最后,调用 handle.handleMessage() 方法来处理消息,也即当派生了子类时需要重写该方法。

3、Handler 构造方法

    之前说过,在线程中使用 Handler 就必须先创建 Looper,通过查看 Handler 的构造方法可知,创建 Handler 时需要一个特定的 Looper 作为参数,如果没有传递 Looper 参数,就直接使用 Looper.myLooper() 方式获取。
    大家知道,Looper 是作用于线程中的,一个线程仅对应一个 Looper,所以由该 Looper 创建的 Handler 和 MessageQueue 必定也是和该线程一一对应的,这也就能用来说明msg.target.dispatchMessage() 方法在处理消息时,一定也是在对应线程中处理的,也即若是在主线程中创建,则 Handler 对应在主线程中处理消息,若在子线程中创建,就会在子线程中处理消息,此时需要注意在这里是不能进行UI更新操作。

public Handler(Looper looper) {
    this(looper, null, false);
}
public Handler(Looper looper, Callback callback, boolean async) {
    mLooper = looper;
    mQueue = looper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}
public Handler(Callback callback, boolean async) {
    // 因为是从 ThreadLocal 中获取,所以是从创建了 Looper 的线程中获取
    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;
}

三、MessageQueue 的工作原理

    消息队列 MessageQueue 主要包含两个操作:插入和读取。读取操作也即取出一条 Message消息,随后这条消息就会从消息队列中移除。
    需要注意得是消息队列内部实现并不是队列,而是通过一个 单链表来处理的(单链表插入和移除有优势)。

1、enqueueMessage(Message, long) 方法

    消息Message 创建后,由 Handler.sendMessage(),然后插入到 MessageQueue,主要源码如下:

boolean enqueueMessage(Message msg, long when) {
    // Handler 对象不能为空
    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) {
        // 调用 Looper.quit()实际是调用 mQueue.quit()终止消息循环
        if (mQuitting) {
            IllegalStateException e = new IllegalStateException(
                    msg.target + " sending message to a Handler on a dead thread");
            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;
}
2、Message next() 方法

    next() 方法是一个无限循环的方法<code>for(;;)</code>,会出现以下几种情况:
(1)当调用 Looper.quit() -> mQueue.quit() 停止消息循环,直接返回 null;
(2)若消息队列中没有消息,next() 方法就会一直被阻塞(如何判断队列中没有消息呢?根据闲置的Handler 个数来判断,当没有闲置的 Handler 时,就阻塞队列?);
(3)当有新消息时,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;
    }
}

四、Message 对象

    Message 也即消息实体,实现了Parcelable接口,所以是可用于进程间通信。
    首先来讲下如何创建 Message的,官方推荐使用 <code>Message.obtain()</code> 或者 <code>Handler.obtainMessage()</code> 方法来创建 Message 对象,而不建议使用构造方法创建,前者是如果回收池中存在,就直接从已回收的对象池中获取,不用重新分配内存,否则就重新创建,后者直接构造,每次都需要从堆中分配内存,具体实现可看 Message.obtain() 方法:

public static Message obtain() {
    synchronized (sPoolSync) {
        // 如果是第一条消息,就会直接创建
        if (sPool != null) { // sPool为静态Message对象
            Message m = sPool;
            sPool = m.next;
            m.next = null;
            m.flags = 0; // clear in-use flag
            sPoolSize--;
            return m;
        }
    }
    return new Message();
}

    sPool 是一个 静态Message 对象,它被赋值是在 Message.recycleUnchecked() 方法中,此方法就是回收一个不再 in-use 的 message,消息回收后,就会清除该 Message.this 的所有信息(成员变量值),并且当消息回收池中的消息的 size 没有超过最大数量 MAX_POOL_SIZE = 50 时,会将回收的该条消息保存在 sPool 中。
由此可知一条 Message 从创建到回收的过程如下:
(1)当使用 Message.obtain() 创建消息时,如果是该线程消息队列中的第一条 Message,就会直接 new Message();
(2)当消息被处理完毕被回收时,会将该条消息的引用保存到 sPool 中,sPoolSize 累计加 1;
(3)当创建第二条消息时,sPool != null,将 sPool 赋值给一个 Message 对象,这样 m就指向了之前回收的对象的内存地址,然后将 sPool 指向下一个被回收的对象,sPoolSize 减 1,,返回对象 m,如此便不用重新申请内存空间。

五、Android 消息处理机制总流程图

消息传递总流程图.png
上一篇 下一篇

猜你喜欢

热点阅读