Handler详解

news2024/10/6 12:24:49

跟Handler有关系的,包括Thread,Looper,Handler,MessageQueue

Looper:

由于Looper是android包加入的类,而Thread是java包的类,所以,想要为Thread创建一个Looper,需要在线程内部调用Looper.prepare

Looper内部会存储一个ThreadLocal,因此每个线程都会有自己的一个Looper。

Looper内部有自己存储了一个MessageQueue,以及主线程的MainLooper。

调用Looper一般会有两个方法:Looper.prepare以及Looper.loop方法

Looper.prepare

prepare会新创建一个Looper,塞进ThreadLocal,因此prepare必须在线程内部调用,才能将线程本身作为key。

同时,会创建MessageQueue,以及存储当前线程。

顺便看下两个比较常用的方法:

myLooper是从ThreadLocal中获取的当前线程所属的Looper。

myQueue对应的是当前线程的Looper中存储的MessageQueue。

Looper.loop

从Looper.loop方法,可以看出几个细节:

  1. 通过调用MessageQueue.next获取下一个要处理的Message
  2. 通过Message.target.dispatchMessage,将Message提交给Message中存储的Handler去处理,Handler调用dispatchMessage
  3. 可以创建一个进程唯一的Observer去监听Message的分配以及处理结束的进度。
public static void loop() {
    final Looper me = myLooper();
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    if (me.mInLoop) {
        Slog.w(TAG, "Loop again would have the queued messages be executed"
                + " before this one completed.");
    }

    me.mInLoop = true;
    final MessageQueue queue = me.mQueue;
    
    for (;;) {
        Message msg = queue.next(); // might block
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }

        // This must be in a local variable, in case a UI event sets the logger
        final Printer logging = me.mLogging;
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
                    msg.callback + ": " + msg.what);
        }
        // Make sure the observer won't change while processing a transaction.
        final Observer observer = sObserver;

        final long traceTag = me.mTraceTag;
        long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
        long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
        if (thresholdOverride > 0) {
            slowDispatchThresholdMs = thresholdOverride;
            slowDeliveryThresholdMs = thresholdOverride;
        }
        final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
        final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

        final boolean needStartTime = logSlowDelivery || logSlowDispatch;
        final boolean needEndTime = logSlowDispatch;

        if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }

        final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
        final long dispatchEnd;
        Object token = null;
        if (observer != null) {
            token = observer.messageDispatchStarting();
        }
        long origWorkSource = ThreadLocalWorkSource.setUid(msg.workSourceUid);
        try {
            msg.target.dispatchMessage(msg);
            if (observer != null) {
                observer.messageDispatched(token, msg);
            }
            dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
        } catch (Exception exception) {
            if (observer != null) {
                observer.dispatchingThrewException(token, msg, exception);
            }
            throw exception;
        } finally {
            ThreadLocalWorkSource.restore(origWorkSource);
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        if (logSlowDelivery) {
            if (slowDeliveryDetected) {
                if ((dispatchStart - msg.when) <= 10) {
                    Slog.w(TAG, "Drained");
                    slowDeliveryDetected = false;
                }
            } else {
                if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
                        msg)) {
                    // Once we write a slow delivery log, suppress until the queue drains.
                    slowDeliveryDetected = true;
                }
            }
        }
        if (logSlowDispatch) {
            showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
        }

        if (logging != null) {
            logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
        }

        // Make sure that during the course of dispatching the
        // identity of the thread wasn't corrupted.
        final long newIdent = Binder.clearCallingIdentity();
        if (ident != newIdent) {
            Log.wtf(TAG, "Thread identity changed from 0x"
                    + Long.toHexString(ident) + " to 0x"
                    + Long.toHexString(newIdent) + " while dispatching to "
                    + msg.target.getClass().getName() + " "
                    + msg.callback + " what=" + msg.what);
        }

        msg.recycleUnchecked();
    }
}

Message

从Looper.loop方法可以看出,会对Looper的MessageQueue遍历,不断取出Message,然后调用Message.target.dispatchMessage方法。

从Message的变量可以看出,target实际是Message所属的Handler。

同时Message存储了一个next,说明MessageQueue是一个链式结构。

MessageQueue

https://www.cnblogs.com/jiy-for-you/p/11707356.html

从MessageQueue.next可以获取几个有效信息:

  1. nativePollOnce:MessageQueue中没有Message的时候会卡在这个方法,类似于object.wait,当有人调用MessageQueue.enqueueMessage方法的时候,会将线程唤醒。
  2. msg.target == null,代表该msg是一个同步屏障(即阻拦同步消息的执行)。遇到同步屏障时,会往后遍历,优先执行异步消息(触发view的绘制的那个消息就是异步消息)。
  3. 如果获取到一个msg,msg.when代表的执行时间还没到,会先去执行IdleHandler里面的消息(或MessageQueue队列为空)。

 

// MessageQueue.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) {// 同步屏障,当遇到同步屏障,会往后寻找异步消息(isAsynchronous)执行
                // Stalled by a barrier.  Find the next asynchronous message in the queue.
                do {// 遍历,直到找到一个异步的msg
                    prevMsg = msg;// 这一步,prevMsg!=null,这会导致
                    msg = msg.next;
                } while (msg != null && !msg.isAsynchronous());
            }
            if (msg != null) {
                if (now < msg.when) {// msg.when是这个message的执行时间,如果message的执行时间在now之后
                    // 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.
            // 走到这,说明消息队列是空的,或队首是一个延迟执行的Message
            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;
    }
}

Handler的总结:

  1. Handler内部一定会有一个Looper。Looper跟线程一一绑定。绑定的关系存在Looper的sThreadLocal中。所以如果Handler想要监听哪个线程上的消息,可以直接给Handler传那个线程的Looper即可。
  2. Looper实际上是一个轮询消息的机制,所以内部一定会存在一个MessageQueue。当Looper开始轮询的时候(调用Looper.loop),会每次调用MessageQueue.next取一个Message出来执行。
  3. Looper获取到Message之后,会调用Message.target.dispatchMessage方法。即实际调用的是Handler.dispatchMessage的方法。
  4. Message中有几个比较重要的参数:
    1. target:这个Message从属于哪个handler(从哪个handler post过去的)。
    2. callback:当调用handler.postRunnable,即创建了一个Message,msg.callBack = runnable。
    3. what:这个Message的唯一标识id。当Handler.handleMessage方法中,会接收多个message,通过what区分这个Message的类别。
    4. when:通过handler.postDelayed,设置这个Message实际应该执行的时间:curTime+delay。MessageQueue的入队实际是通过when去进行Message的排序的。
  5. handler.dispatchMessage方法,
    1. 如果Message.callback != null,直接执行Message.callback.run(即post(Runnable))中Runnable的执行。
    2. 否则如果给handler设置了Callback,就调用Callback.handleMessage
    3. 否则,调用Handler本身的handleMessage方法(空实现),需要重写。

关于barrier

// MessageQueue
private int postSyncBarrier(long when) {
    // Enqueue a new sync barrier token.
    // We don't need to wake the queue because the purpose of a barrier is to stall it.
    synchronized (this) {
        final int token = mNextBarrierToken++;
        final Message msg = Message.obtain();
        msg.markInUse();
        msg.when = when;
        msg.arg1 = token;// 代表Message的barrier,特征是target == null

        Message prev = null;
        Message p = mMessages;
        if (when != 0) {// 根据when,将代表barrier的msg插入MessageQueue
            while (p != null && p.when <= when) {
                prev = p;
                p = p.next;
            }
        }
        if (prev != null) { // invariant: p == prev.next
            msg.next = p;
            prev.next = msg;
        } else {
            msg.next = p;
            mMessages = msg;
        }
        return token;
    }
}

postSyncBarrier,生成一个target == null的Message,根据when,插入MessageQueue中。返回的token是barrier的唯一标识。只要postSyncBarrier,就要根据这个token,后面移除barrier。否则会导致同步消息一直无法执行。

看下有了barrier的MessageQueue取Message的时候是怎么表现的。

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);// 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) {// 如果取msg的时候,队首的Msg是Barrier
                // Stalled by a barrier.  Find the next asynchronous message in the queue.
                do {
                    prevMsg = msg;
                    msg = msg.next;
                    // 就一直往后遍历,寻找一个异步的msg
                } while (msg != null && !msg.isAsynchronous());
            }
            if (msg != null) {
                if (now < msg.when) {// 如果还没到msg的执行时间,就设置nextPollTimeoutMillis
                    // 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 {// 如果mMessages队列为空,或有Barrier的时候,异步msg为空,就设置等待时间为-1
            // 为-1代表等待被唤醒
                // 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();
            }// 如果队列为空,或者还没到message的执行时间,开始执行IdleHandler
            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.
        // 防止下次再走一遍IdleHandler
        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.
        // 经过IdleHandler之后,可能已经有Message入队了,再遍历一遍,第二次就直接等待了。
        nextPollTimeoutMillis = 0;
    }
}

总结下next的逻辑:

  1. 如果mMessages的队首是barrier(msg.target == null),就遍历messages,优先执行异步消息(异步消息一般是优先级最高的信息:比如响应input事件或是view刷新。)。
  2. 如果不是barrier,就直接取队首的message执行。
  3. 如果1,2步骤取到的message != null,先看message的when < now,大于则直接返回message给Looper.loop方法。小于,则设置nextPollTimeoutMillis,用来设置线程的等待时间:nativePollOnce。
  4. 如果messageQueue为空,或message.when > now(即要等待),那么这个时候,就去执行IdleHandler。

总结下上面,nativePollOnce其实代表,线程在等待下一个消息的执行,或者messages队列为空。或者是设置了barrier情况下,没有异步消息的时候。

下一步,看下MessageQueue的具体打出日志代表什么。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/878808.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

ChatGPT能代替搜索引擎吗?ChatGPT和搜索引擎有什么区别?

ChatGPT和搜索引擎是两种在信息获取和交流中常用的工具&#xff0c;ChatGPT是一种基于人工智能技术的聊天机器人&#xff0c;而搜索引擎是一种在互联网上搜索信息的工具。尽管它们都是依托互联网与信息获取和交流有关&#xff0c;部分功能重合&#xff0c;但在很多方面存在着明…

名侦探番外——Arduino“炸弹”引爆摩天大楼

名侦探番外——Arduino“炸弹”引爆摩天大楼 硬件准备1.材料准备2.模块介绍 电路设计1.硬件接线 程序设计1.设计思路2.部分程序3.功能优化 总结 好久不见&#xff0c;童鞋们&#xff01;小编突然想到很久以前看的柯南剧场版——计时引爆摩天大楼的情景&#xff0c;对剧里的“炸…

TEXTure环境配置,跑通inference的demo

TEXTure 环境配置安装kaolin这个包,这里可能会遇到各种问题配置huggingface的访问令牌 运行Text Conditioned Texture Generation指令报错1报错2成功运行 查看结果查看贴图后的三维网格模型 环境配置 # 创建一个名为texture的环境 conda create -n texture python3.9 -y# 激活…

【算法——双指针】LeetCode 202 快乐数

题目描述&#xff1a; 思路&#xff1a;快慢指针 看到循环&#xff0c;我就想起了快慢指针的方法&#xff0c;从题目我们可以看出&#xff0c;我们需要模拟一个过程&#xff1a;不断用当前的数去生成下一个数&#xff0c;生成的规则就是将当前数的各位的平方累加&#xff1b; …

微信小程序(原生)搜索功能实现

一、效果图 二、代码 wxml <van-searchvalue"{{ keyword }}"shape"round"background"#000"placeholder"请输入关键词"use-action-slotbind:change"onChange"bind:search"onSearch"bind:clear"onClear&q…

Python——添加照片边框

原图&#xff1a; 添加边框后&#xff1a; 添加边框会读取照片的exif信息如时间、相机型号、品牌以及快门焦段等信息&#xff0c;将他们显示在下面的边框中。 获取当前py文件路径 import os #get path that py file located def Get_Currentpath():file_path os.path.abspa…

mysql主从复制搭建

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言MySQL复制过程分为三部&#xff1a; 一、准备工作二、配置>主库Master三、配置>从库SlaveSlave_IO_Running: YesSlave_SQL_Running: Yes 四、测试至此&am…

htmlCSS-----弹性布局案例展示

目录 前言 效果展示 ​编辑 代码 思路分析 前言 上一期我们学习了弹性布局&#xff0c;那么这一期我们用弹性布局来写一个小案例&#xff0c;下面看代码&#xff08;上一期链接html&CSS-----弹性布局_灰勒塔德的博客-CSDN博客&#xff09; 效果展示 代码 html代码&am…

BeanFactoryApplicationContext之间的关系

1**.BeanFactory与ApplicationContext之间的关系** &#xff08;1&#xff09;从继承关系上来看&#xff1a; ​ BeanFactory它是ApplicationContext 的父接口 &#xff08;2&#xff09;从功能上来看&#xff1a; ​ BeanFactory才是spring中的核心容器&#xff0c;而Appli…

使用AffNet和HardNet进行图像匹配

一、说明 我们有一个任务是找到与给定查询图像最匹配的图像。首先&#xff0c;我们在OpenCV中尝试了使用SIFT描述符和基于Flann的匹配器的经典图像匹配。结果是完全错误的。然后是词袋...最后&#xff0c;找到了AffNet和HardNet。 二、关于AffNet和HardNet 本文专门介绍如何进…

什么是浮动(float)?如何清除浮动?

聚沙成塔每天进步一点点 ⭐ 专栏简介⭐ 浮动&#xff08;Float&#xff09;和清除浮动⭐ 浮动的使用⭐ 清除浮动1. 空元素法&#xff08;Empty Element Method&#xff09;2. 使用 Clearfix Hack3. 使用 Overflow ⭐ 写在最后 ⭐ 专栏简介 前端入门之旅&#xff1a;探索Web开发…

《Java-SE-第三十七章》之反射

前言 在你立足处深挖下去,就会有泉水涌出!别管蒙昧者们叫嚷:“下边永远是地狱!” 博客主页&#xff1a;KC老衲爱尼姑的博客主页 博主的github&#xff0c;平常所写代码皆在于此 共勉&#xff1a;talk is cheap, show me the code 作者是爪哇岛的新手&#xff0c;水平很有限&…

【Vue-Router】嵌套路由

footer.vue <template><div><router-view></router-view><hr><h1>我是父路由</h1><div><router-link to"/user">Login</router-link><router-link to"/user/reg" style"margin-left…

Selenium 测试用例编写

编写Selenium测试用例就是模拟用户在浏览器上的一系列操作&#xff0c;通过脚本来完成自动化测试。 编写测试用例的优势&#xff1a; 开源&#xff0c;免费。 支持多种浏览器 IE&#xff0c;Firefox&#xff0c;Chrome&#xff0c;Safari。 支持多平台 Windows&#xff0c;Li…

【C语言】const修饰普通变量和指针

大家好&#xff0c;我是苏貝&#xff0c;本篇博客是系列博客每日一题的第一篇&#xff0c;本系列的题都不会太难&#xff0c;如果大家对这种系列的博客感兴趣的话&#xff0c;可以给我一个赞&#x1f44d;吗&#xff0c;感谢❤️ 文章目录 一.const修饰普通变量二.const修饰指…

Spring事务控制

目录 1、什么是事务控制 2、编程式事务控制 2.1、简介 2.2、相关对象 2.2.1、PlatformTransactionManager 2.2.2、TransactionDefinition 2.2.2.1、事务隔离级别 2.2.2.2、事务传播行为 2.2.3、TransactionStatus 3、声明式事务控制 3.1、简介 3.2、区别 3.3、⭐作…

Unity实现异步加载场景

一&#xff1a;创建UGUI 首先我们在LoginCanvas登入面板下面创建一个Panel,取名为LoadScreen,再在loadScreen下面创建一个Image组件&#xff0c;放置背景图片&#xff0c;然后我们再在lpadScreen下面继续创建一个Slider,这个是用来加载进度条的&#xff0c;我们改名为LoadSlid…

【考研数学】概率论与数理统计 | 第一章——随机事件与概率(1)

文章目录 一、随机试验与随机事件1.1 随机试验1.2 样本空间1.3 随机事件 二、事件的运算与关系2.1 事件的运算2.2 事件的关系2.3 事件运算的性质 三、概率的公理化定义与概率的基本性质3.1 概率的公理化定义3.2 概率的基本性质 写在最后 一、随机试验与随机事件 1.1 随机试验 …

Docker-使用数据卷、文件挂载进行数据存储与共享

一、前言 默认情况下&#xff0c;在Docker容器内创建的所有文件都只能在容器内部使用。容器删除后&#xff0c;数据也跟着删除&#xff0c;虽然通常我们不会删除容器&#xff0c;但是一旦宿主机发生故障&#xff0c;我们重新创建容器恢复服务&#xff0c;那么之前容器创建的文…

Matlab图坐标轴数值负号改为减号(change the hyphen (-) into minus sign (−, “U+2212”))

在MATLAB中&#xff0c;坐标轴负数默认符号是 - &#xff0c;如下图所示 x 1:1:50; y sin(x); plot(x,y)可通过以下两语句将负号修改为减号&#xff1a; set(gca,defaultAxesTickLabelInterpreter,latex); yticklabels(strrep(yticklabels,-,$-$));或者 set(gca, TickLabe…