当前位置: 首页 > news >正文

Handler消息机制

Handler是用来发送和处理MessageRunnable的,每个Handler实例都是与一个线程和该线程的消息队列相关联的,如果当前线程没有创建Looper有可能会抛异常。有可能的意思是有两种情况:

  • 当前线程没有创建Looper,直接调用无参构造Handler()则会抛异常;
  • 当前线程没有创建Looper,调用Looper.loop()则会抛异常。

创建Handler、Looper和MessageQueue

    public Handler() {
        this(null, false);
    }
    public Handler(Callback callback) {
        this(callback, false);
    }
复制代码

这两个构造器都是在当前线程创建Handler,我们通常会使用第一个方法创建Handler;第二个是设置一个处理MessageCallback接口。

    public Handler(Callback callback, boolean async) {
       ...

        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;
        //是否异步,默认false
        mAsynchronous = async;
    }
复制代码

上面两个构造器最终都会执行这个构造器,mLooper是使用Looper.myLooper()赋值的,如果为空会抛出RuntimeException,然后将LoopermQueue赋值给HandlermQueuemQueue就是消息队列。再看一下Looper.myLooper()

    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }
复制代码

可以看到Looper是通过ThreadLocal<Looper> sThreadLocal获取到的,这里先介绍一下ThreadLocal的两个主要方法,过多细节不介绍:

    public void set(T value) {
        //获取当前线程
        Thread t = Thread.currentThread();
        //根据t获取ThreadLocalMap,key是ThreadLocal类型
        ThreadLocalMap map = getMap(t);
        if (map != null)
            //如果map不为空,直接设置
            map.set(this, value);
        else
            //如果map为空,创建新的map,再把value放进去,本篇放的值是Looper对象
            createMap(t, value);
    }
    
    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();
    }
复制代码

上面代码挺简单的就不做解释了,具体介绍一下 ThreadLocal: 这个类提供线程局部变量,ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。 话又说回来,那么什么时候把Looper设置到ThreadLocal<Looper> sThreadLocal里的?其实是在app启动的时候就设置了,下面是ActivityThreadmain方法:

    public static void main(String[] args) {
        ...

        Looper.prepareMainLooper();

        ...
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }
复制代码

这里调用了Looper.prepareMainLooper(),然后又会调用prepare(false),创建新的Looper,并将它设置到sThreadLocal里。这里主线程的Looper就创建完成了,接着调用Looper.loop()开始轮询,这个后面再讲。

    public static void prepareMainLooper() {
        //主线程Looper不允许退出
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                //因为一个线程只能有一个Looper
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }
    
    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        //将新的Looper设置到ThreadLocal里
        sThreadLocal.set(new Looper(quitAllowed));
    }
    
    private Looper(boolean quitAllowed) {
        //创建消息队列
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }
复制代码

这里注意一下上面的quitAllowed参数,这个参数在主线程里是false,表示Looper不允许退出,否则抛出IllegalStateException("Main thread not allowed to quit.")。到了这里,主线程创建LooperHandlerMessageQueue就介绍完了。

    public Handler(Looper looper) {
        this(looper, null, false);
    }
    public Handler(Looper looper, Callback callback) {
        this(looper, callback, false);
    }
复制代码

这两个构造器可以在任意线程创建Handler,主线程使用Looper.myLooper(),子线程使用Looper.prepare()

    public static void prepare() {
        //这里的quitAllowed参数是true,表示Looper允许退出
        prepare(true);
    }
复制代码
    public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }
复制代码

这里比较简单就是进行赋值,创建完不要忘记调用Looper.loop()开始轮询。注意:不使用时要调用Looper.quit()Looper.quitSafely(),前者是移除消息队列中所有消息,后者是移除未触发的消息。否则Looper会处于等待状态。

发送消息

    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);
    }
    
        public final boolean sendMessageAtFrontOfQueue(Message msg) {
        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, 0);
    }
复制代码

无论调用哪一种发送消息的方法都会走到这两个方法,只是第二个方法的uptimeMillis为0,表示需要立即执行。下面看一下enqueueMessage:

    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            //设置异步
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
复制代码

这里注意msg.target就是Handler,然后交给MessageQueueenqueueMessage插入消息队列。

插入消息

    boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            //如果Handler为空抛出异常
            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()时为true
            if (mQuitting) {
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
                //消息回收
                msg.recycle();
                return false;
            }
            //标记消息已经被使用
            msg.markInUse();
            //设置消息的运行时间
            msg.when = when;
            //设置当前的消息
            Message p = mMessages;
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {
                // 当前消息队列为空或when == 0或运行时间小于p的运行时间就插入到头部.
                msg.next = p;
                mMessages = msg;
                //needWake需要根据mBlocked的情况考虑是否触发
                needWake = mBlocked;
            } else {
                //当前消息队列不为空,并且不需要立即运行,并且当前运行时间>=p的运行时间
                //插入队列中间,我们不必唤醒事件队列,除非队列头部存在障碍并且消息是队列中最早的异步消息。
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                //开始循环直到当前消息为空,或者运行时间小于p的运行时间
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        //因为消息队列之前还剩余消息,所以这里不用调用nativeWakeup
                        needWake = false;
                    }
                }
                // 将msg按照时间顺序插入消息队列,p - msg - next
                msg.next = p; 
                prev.next = msg;
            }
            if (needWake) {
                //调用nativeWake,以触发nativePollOnce函数结束等待
                nativeWake(mPtr);
            }
        }
        return true;
    }
复制代码

MessageQueue是按照Message触发时间的先后顺序排列的,队头的消息是将要最早触发的消息。当有消息需要加入消息队列时,会从队列头开始遍历,直到找到消息应该插入的合适位置,以保证所有消息的时间顺序。那么插入到队列中的消息是如何取出来的呢?当然是Looper.loop()啦,

取出消息

    public static void loop() {
        final Looper me = myLooper();
        if (me == null) {
            //如果当前线程没有Looper抛出异常
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;

        ...

        for (;;) {
            // 通过next方法取出消息,这里是关键,我们后面分析,先说一点next没有消息会一直处于阻塞状态,
            // 所以不会往下走
            Message msg = queue.next();
            if (msg == null) {
                // 没有消息表明消息队列正在退出。
                return;
            }
            ...
            //分发取出的消息,这里msg.target就是Handler
            msg.target.dispatchMessage(msg);
            ...
            //处理过之后要把消息回收
            msg.recycleUnchecked();
        }
    }
复制代码

接下来我们去看看MessageQueuenext()

    Message next() {
        // 如果消息队列执行了quit或dispose就会返回空的消息
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // 循环迭代的首次为-1
        //如果为-1,则表示无限等待,直到有事件发生为止。如果值为0,则无需等待立即返回
        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 {
                        // 获取一个消息并返回,把msg.next设置成当前消息.
                        //如果取到了消息mBlocked为false,没取到就是
                        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的使用状态
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // 没有找到消息.
                    nextPollTimeoutMillis = -1;
                }

                // 如果消息正在推出,返回null.
                if (mQuitting) {
                    dispose();
                    return null;
                }

              if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    //第一次迭代,并且消息队列为空或者是第一个消息
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // 没有 idle handlers 需要执行.  处于等待状态并跳过这次迭代.
                    mBlocked = true;
                    continue;
                }
            
            ...

            //重置idle handler个数为0,以保证不会再次重复运行
            pendingIdleHandlerCount = 0;
            //当调用一个空闲handler时,一个新message能够被分发,因此无需等待可以直接查询pending message.
            nextPollTimeoutMillis = 0;
        }
    }
复制代码

这样消息就被取出来了,接下来看看是如何处理消息的。

处理消息

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

如果msgcallback不为空,则执行handleCallback(msg);否则看HandlermCallback是否为空,不为空则执行mCallback.handleMessage(msg),若mCallback.handleMessage(msg)返回true则直接退出方法,否则执行handleMessage(msg)handleMessage(msg)是个空方法,需要我们自己来实现。

相关文章:

  • 数字货币交易系统火爆的背后是政策的大力支持
  • dnspython模块常见用法
  • hadoop 的组建概述
  • RxJava -- fromArray 和 Just 以及 interval
  • ifup em2启动网卡时报错:connection activation failed
  • BOOST.ASIO源码剖析(一)
  • iis web.config 配置示例
  • 不要仅为85%的用户设计:关注无障碍设计
  • 猫头鹰的深夜翻译:Java 2D Graphics, 简单的仿射变换
  • Oracle安装时,已有oracle用户,将用户添加到oinstall和dba用户组
  • freenom域名解析与次级域名
  • 面试题:给你个id,去拿到name,多叉树遍历
  • 前端CORS请求梳理
  • osquery简单试用
  • 关于Java中分层中遇到的一些问题
  • “寒冬”下的金三银四跳槽季来了,帮你客观分析一下局面
  • Computed property XXX was assigned to but it has no setter
  • Date型的使用
  • Golang-长连接-状态推送
  • HTTP那些事
  • Javascripit类型转换比较那点事儿,双等号(==)
  • Java小白进阶笔记(3)-初级面向对象
  • JS数组方法汇总
  • Laravel Mix运行时关于es2015报错解决方案
  • leetcode388. Longest Absolute File Path
  • magento2项目上线注意事项
  • Python socket服务器端、客户端传送信息
  • spring学习第二天
  • Traffic-Sign Detection and Classification in the Wild 论文笔记
  • vue中实现单选
  • Yii源码解读-服务定位器(Service Locator)
  • 纯 javascript 半自动式下滑一定高度,导航栏固定
  • 短视频宝贝=慢?阿里巴巴工程师这样秒开短视频
  • 那些年我们用过的显示性能指标
  • 前端知识点整理(待续)
  • 如何解决微信端直接跳WAP端
  • 适配iPhoneX、iPhoneXs、iPhoneXs Max、iPhoneXr 屏幕尺寸及安全区域
  • 为什么要用IPython/Jupyter?
  • 看到一个关于网页设计的文章分享过来!大家看看!
  • 交换综合实验一
  • ​HTTP与HTTPS:网络通信的安全卫士
  • (31)对象的克隆
  • (51单片机)第五章-A/D和D/A工作原理-A/D
  • (C#)一个最简单的链表类
  • (done) ROC曲线 和 AUC值 分别是什么?
  • (Matlab)使用竞争神经网络实现数据聚类
  • (搬运以学习)flask 上下文的实现
  • (二)什么是Vite——Vite 和 Webpack 区别(冷启动)
  • (附源码)springboot课程在线考试系统 毕业设计 655127
  • (九十四)函数和二维数组
  • (三)uboot源码分析
  • (四)Android布局类型(线性布局LinearLayout)
  • (转) SpringBoot:使用spring-boot-devtools进行热部署以及不生效的问题解决
  • (转)Linux下编译安装log4cxx
  • (转)程序员疫苗:代码注入