android消息机制

1、消息机制概述

一、消息机制的简介

在Android中使用消息机制,最早能想到的就是Handler。git

Handler是Android消息机制的上层接口。Handler的使用过程很简单,经过它能够轻松地将一个任务切换到Handler所在的线程中去执行。一般状况下,Handler的使用场景是更新UI。github

即在子线程汇总,进行耗时操做,执行完后发送消息通知主线程更新UI。bash

这即是消息机制的典型应用场景。数据结构


二、消息机制的模型

消息机制主要包含:MessageQueue、Handler和Looper这三个部分,以及Message架构

  • “Message”:须要传递的消息,能够传递数据;
  • “MessageQueue”:消息队列,可是它的内部实现机制是经过单链表的数据结构来维护消息对垒,由于单链表在插入和删除上比较有优点。主要功能向消息池投递消息(MessageQueue.enqueueMessage())和取走消息池的消息(MessageQueue.next()
  • “Handler”:消息复制类,主要功能向消息池发送各类消息事件(Handler.sendMessage())和处理对应消息事件(Handler.handleMessage())
  • Looper:不断循环执行(Looper.loop()),从MessageQueue中读取消息,按分发机制将消息分发给目标处理者。


三、消息机制的架构

消息机制的运行流程:异步

  • 在子线程执行完耗时操做,经过Handler.sendMessage()Handler.postMessage()发送消息,MessageQueue.enqueueMessage()方法将消息添加到消息队列中。当经过Looper.loop()开启循环后,会不断地从线程池中读取消息,即调用MessageQueue.next(),然后调用目标Handler(即发送该消息的Handler)的dispatchMessage()方法传递消息,而后返回到Handler所在的线程(能够是主线程也能够是子线程),目标Handler收到消息,调用handleMessage()方法,接受消息,处理消息。

图片来源async


MessageQueue、Handler和Looper三者之间的关系:每一个线程中只能存在一个Looper一个Looper是保存在ThreadLocal中的。主线程(UI线程)已经建立了一个Looper,因此在主线程中不须要再建立Looper,可是在其余线程中须要建立Looper。ide

每一个线程能够有多个Handler,即一个Looper能够处理多个Handler的消息。Looper中维护一个MessageQueue,来维护消息对垒,消息队列的Message能够来自不一样的Handler。oop


2、消息机制的源码分析

一、Looper

要想使用消息机制,首先要建立一个Looper源码分析

  • 初始化Looper

无参数状况下,默认调用prepare(true):表示的是这个Looper能够退出,而对于false的状况则表示当前Looper不能够退出。

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,则会抛出异常,从而代表只能存在一个Looper,并报错在ThreadLocal中。

其中ThreadLocal是线程本地存储区(Thread Local Storage,TLS),每一个线程都有本身的私有的本地存储区域,不一样线程之间彼此不能访问对方的TLS区域。


  • 开启Looper

public static void loop() {
    final Looper me = myLooper();  //获取TLS存储的Looper对象 
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    final MessageQueue queue = me.mQueue;  //获取Looper对象中的消息队列

    Binder.clearCallingIdentity();
    final long ident = Binder.clearCallingIdentity();

    for (;;) { //进入loop的主循环方法
        Message msg = queue.next(); //可能会阻塞,由于next()方法可能会无限循环
        if (msg == null) { //消息为空,则退出循环
            return;
        }

        Printer logging = me.mLogging;  //默认为null,可经过setMessageLogging()方法来指定输出,用于debug功能
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
                    msg.callback + ": " + msg.what);
        }
        msg.target.dispatchMessage(msg); //获取msg的目标Handler,而后用于分发Message 
        if (logging != null) {
            logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
        }

        final long newIdent = Binder.clearCallingIdentity();
        if (ident != newIdent) {
         
        }
        msg.recycleUnchecked(); 
    }
}复制代码

loop()进入循环模式,不断重复下面的操做,直到消息为空时退出循环;

读取MessageQueue的下一条Message(关于next(),后面详细介绍);

把Message分发给对应的target(该target,即为handler

当next()取出下一条消息时,若队列中没有消息时,则next()会无限循环,产生阻塞。等待MessageQueue中加入消息,而后从新唤醒

主线程中不须要本身建立Looper,由于在程序启动时,系统已经帮咱们自动调用了Looper.prepare()方法。查看ActivityThread中的main()方法,以下:

public static void main(String[] args) {
    ..................
    Looper.prepareMainLooper();
    ..................
    Looper.loop();
    ..................
}复制代码

其中“prepareMainLooper()”方法会调用prepare(false)


二、Handler

  • 建立Handler

public Handler() {
    this(null, false);
}

public Handler(Callback callback, boolean async) {
   .................................
    //必须先执行Looper.prepare(),才能获取Looper对象,不然为null.
    mLooper = Looper.myLooper();  //从当前线程的TLS中获取Looper对象
    if (mLooper == null) {
        throw new RuntimeException("");
    }
    mQueue = mLooper.mQueue; //消息队列,来自Looper对象
    mCallback = callback;  //回调方法
    mAsynchronous = async; //设置消息是否为异步处理方式
}复制代码

对于Handler的无参构造方法,默认采用当前线程TLS中的Looper对象,而且callback()回调方法为null,且消息为同步处理方法。只要执行的Looper.prepare方法,那么即可以得到有效的Looper对象。


三、发送消息

发送消息有几种 方法,但归根到底都是调用了sendMessageAtTime()方法

在子线程中经过Handler的post()方法或send()方法发送消息,最终都会调用sendMessageAtTime()方法

  • post()方法

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

public final boolean postAtTime(Runnable r, long uptimeMillis){
   return sendMessageAtTime(getPostMessage(r), uptimeMillis);
}

 public final boolean postAtTime(Runnable r, Object token, long uptimeMillis){
    return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
}

 public final boolean postDelayed(Runnable r, long delayMillis){
    return sendMessageDelayed(getPostMessage(r), delayMillis);
}

public final boolean sendMessageDelayed(Message msg, long delayMillis){
    if (delayMillis < 0) {
        delayMillis = 0;
    }
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}复制代码

就连子线程中调用Activity中的runOnUiThread()中更新UI,其实也是发送消息通知主线程更新UI,最终也会调用sendMessageAtTime()方法。

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

若是当前线程不等于UI线程(主线程),就去调用Handler的post()方法,最终也会调用sendMessageAtTime()方法。不然就直接调用Runnable对象的run()方法。


sendMessageAtTime()源码:

public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
    //其中mQueue是消息队列,从Looper中获取的
    MessageQueue queue = mQueue;
    if (queue == null) {
        RuntimeException e = new RuntimeException(
                this + " sendMessageAtTime() called with no mQueue");
        Log.w("Looper", e.getMessage(), e);
        return false;
    }
    //调用enqueueMessage方法
    return enqueueMessage(queue, msg, uptimeMillis);
}复制代码

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    //调用MessageQueue的enqueueMessage方法
    return queue.enqueueMessage(msg, uptimeMillis);
}复制代码

能够看到SendMessageAtTime()方法的做用很简单,就是调用MessageQueue的enqueueMessage()方法,往消息队列中添加一个消息。

下面来看enqueueMessage()方法的具体执行逻辑。

enqueueMessage()

boolean enqueueMessage(Message msg, long when) {
    // 每个Message必须有一个target
    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) {  //正在退出时,回收msg,加入到消息池
            msg.recycle();
            return false;
        }
        msg.markInUse();
        msg.when = when;
        Message p = mMessages;
        boolean needWake;
        if (p == null || when == 0 || when < p.when) {
            //p为null(表明MessageQueue没有消息) 或者msg的触发时间是队列中最先的, 则进入该该分支
            msg.next = p;
            mMessages = msg;
            needWake = mBlocked; 
        } else {
            //将消息按时间顺序插入到MessageQueue。通常地,不须要唤醒事件队列,除非
            //消息队头存在barrier,而且同时Message是队列中最先的异步消息。
            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;
            prev.next = msg;
        }
        if (needWake) {
            nativeWake(mPtr);
        }
    }
    return true;
}复制代码

MessageQueue是按照Message触发事件前后顺序排序的,队头的消息是将要最先触发的消息。当有消息须要加入消息队列时,会从队列头开始遍历,直到找到消息应该插入的合适位置,以保证全部消息的时间顺序。


四、获取消息

当发送了消息后,在MessageQueue维护了消息队列,而后在Looper中经过loop()方法,不断地获取消息。上面对loop()方法进行了介绍,其中最重要的是调用了queue.next()方法,经过该方法来提取下一条信息。下面咱们来看next()方法的具体流程。

  • next()

Message next() {
    final long ptr = mPtr;
    if (ptr == 0) { //当消息循环已经退出,则直接返回
        return null;
    }
    int pendingIdleHandlerCount = -1; // 循环迭代的首次为-1
    int nextPollTimeoutMillis = 0;
    for (;;) {
        if (nextPollTimeoutMillis != 0) {
            Binder.flushPendingCommands();
        }
        //阻塞操做,当等待nextPollTimeoutMillis时长,或者消息队列被唤醒,都会返回
        nativePollOnce(ptr, nextPollTimeoutMillis);
        synchronized (this) {
            final long now = SystemClock.uptimeMillis();
            Message prevMsg = null;
            Message msg = mMessages;
            if (msg != null && msg.target == null) {
                //当消息Handler为空时,查询MessageQueue中的下一条异步消息msg,为空则退出循环。
                do {
                    prevMsg = msg;
                    msg = msg.next;
                } while (msg != null && !msg.isAsynchronous());
            }
            if (msg != null) {
                if (now < msg.when) {
                    //当异步消息触发时间大于当前时间,则设置下一次轮询的超时时长
                    nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                } else {
                    // 获取一条消息,并返回
                    mBlocked = false;
                    if (prevMsg != null) {
                        prevMsg.next = msg.next;
                    } else {
                        mMessages = msg.next;
                    }
                    msg.next = null;
                    //设置消息的使用状态,即flags |= FLAG_IN_USE
                    msg.markInUse();
                    return msg;   //成功地获取MessageQueue中的下一条即将要执行的消息
                }
            } else {
                //没有消息
                nextPollTimeoutMillis = -1;
            }
         //消息正在退出,返回null
            if (mQuitting) {
                dispose();
                return null;
            }
            ...............................
    }
}复制代码

nativePossOnce()是阻塞操做,其中nextPollTimeoutMillis表明下一个消息到来前,还须要等待的时长;当nextPollTimeoutMillis=-1时,表示消息队列中无消息,会一直等待下去

能够看出next()方法根据消息的触发事件,获取下一条须要执行的消息队列中消息为空时,则会进行阻塞操做。


五、分发信息

在loop()方法中,获取到下一条信息后,执行msg.target.dispatchMessage(msg),来分发消息到目标Handler对象。

  • dispatchMessage()

public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        //当Message存在回调方法,回调msg.callback.run()方法;
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            //当Handler存在Callback成员变量时,回调方法handleMessage();
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        //Handler自身的回调方法handleMessage()
        handleMessage(msg);
    }
}复制代码

private static void handleCallback(Message message) {
    message.callback.run();
}复制代码

分发消息流程:

当Message的msg.callback不为空时,则回调方法msg.callback.run()

当Handler的mCallback不为空时,则回调方法mCallback.handleMessage(msg);

最后调用Handler自身的回调方法handleMessage(),该方法默认为空,Handler子类经过覆盖该方法来完成具体的逻辑

消息分发的优先级:

Message的回调方法:message.callback.run(),优先级最高。

Handler中Callback的回调方法:Handler.mCallback.handleMessage(msg),优先级仅次于message.callback.run()

Handler的默认方法:Handler.handleMessage(),优先级最低

对于不少状况下,消息分发后的处理方法时第3种,即Handler.handleMessage(),通常地每每经过重写该方法从而实现本身的业务逻辑。

相关文章
相关标签/搜索