温故知新:探究Android UI 绘制刷新流程

news2024/10/6 8:41:00

一、说明:

  1. 基于之前的了解知道ui的绘制最终会走到Android的ViewRootImplscheduleTraversals进行发送接收vsync信号绘制,在ViewRootImpl中还会进行主线程检测,也就是我们所谓子线程更新ui会抛出异常。

  2. 像我们常用的刷新ui,invalidate,requestLayout方法,(按我之前的理解在ViewRootImpl初始化添加后,在子线程中刷新ui一定会崩溃:如下图)

二、问题:invalidate一定会导致异常崩溃?

2.1、例子:子线程更新TextView文本(注意这里是TextView,为什么是它而不是ImageView,因为我的背景就是使用的TextView,使用它的时候发现了invalidate,requestLayout方法的区别 )

某天我在onResume中利用子线程更新了TextView的一段代码,发现并没有抛出异常崩溃,代码如下:

 override fun onResume() {
        super.onResume()
        mBind.btTest.setOnClickListener{
            lifecycleScope.launch(Dispatchers.IO) {
                mBind.btTest.text = "子线程点击改变:${Thread.currentThread().name}"
            }
        }
    }

我在想为什么呢?,看代码: 一步步debug:TextView控件中:

1.、
public final void setText(CharSequence text) {
    setText(text, mBufferType);
}
2.、
public void setText(CharSequence text, BufferType type) {
    setText(text, type, true, 0);

    if (mCharWrapper != null) {
        mCharWrapper.mChars = null;
    }
}
3.、
private void setText(CharSequence text, BufferType type,
                     boolean notifyBefore, int oldlen) {
     ...省略
    if (mLayout != null) {
        checkForRelayout();
    }
    ...省略
    
}

以上主要看第三步中的 checkForRelayout()检测是否需要重绘,方法如下

@UnsupportedAppUsage
private void checkForRelayout() {
    // If we have a fixed width, we can just swap in a new text layout
    // if the text height stays the same or if the view height is fixed.

    if ((mLayoutParams.width != LayoutParams.WRAP_CONTENT
            || (mMaxWidthMode == mMinWidthMode && mMaxWidth == mMinWidth))
            && (mHint == null || mHintLayout != null)
            && (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight() > 0)) {
        // Static width, so try making a new text layout.

        int oldht = mLayout.getHeight();
        int want = mLayout.getWidth();
        int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth();

        /*
         * No need to bring the text into view, since the size is not
         * changing (unless we do the requestLayout(), in which case it
         * will happen at measure).
         */
        makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING,
                      mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(),
                      false);
        
        //1.检测文本的显示类型,就是我们的过长省略号这种
        if (mEllipsize != TextUtils.TruncateAt.MARQUEE) {
            // In a fixed-height view, so use our new text layout.
            if (mLayoutParams.height != LayoutParams.WRAP_CONTENT
                    && mLayoutParams.height != LayoutParams.MATCH_PARENT) {
                autoSizeText();
                invalidate();
                return;
            }

            // Dynamic height, but height has stayed the same,
            // so use our new text layout.
            if (mLayout.getHeight() == oldht
                    && (mHintLayout == null || mHintLayout.getHeight() == oldht)) {
                autoSizeText();
                invalidate();
                return;
            }
        }

        // We lose: the height has changed and we have a dynamic height.
        // Request a new view layout using our new text layout.
        requestLayout();
        invalidate();
    } else {
        // Dynamic width, so we have no choice but to request a new
        // view layout with a new text layout.
        nullLayouts();
        requestLayout();
        invalidate();
    }
}

从上面的checkForRelayout()方法中的if (mEllipsize != TextUtils.TruncateAt.MARQUEE)条件知道成立,因为我们没有设置过mEllipsize = 跑马灯效果,所以走了invalidate()方法然后直接return截断,不会走后面的requestLayout()方法,至于requestLayout() 与 invalidate()的区别我就不讲了

2.2、分析requestLayout方法

基于之前的知识我知道调用requestLayout()方法会崩溃,至于为什么调用requestLayout()方法会崩溃?

我们先看requestLayout()方法,暂停一会invalidate()的跟进

requestLayout()方法代码如下:

public void requestLayout() {
    if (mMeasureCache != null) mMeasureCache.clear();

    if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
        // Only trigger request-during-layout logic if this is the view requesting it,
        // not the views in its parent hierarchy
        ViewRootImpl viewRoot = getViewRootImpl();
        if (viewRoot != null && viewRoot.isInLayout()) {
            if (!viewRoot.requestLayoutDuringLayout(this)) {
                return;
            }
        }
        mAttachInfo.mViewRequestingLayout = this;
    }

    mPrivateFlags |= PFLAG_FORCE_LAYOUT;
    mPrivateFlags |= PFLAG_INVALIDATED;

    if (mParent != null && !mParent.isLayoutRequested()) {
        mParent.requestLayout();
    }
    if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
        mAttachInfo.mViewRequestingLayout = null;
    }
}

requestLayout()方法中会循环递归调用 mParent.requestLayout()方法,直到找到ViewRootImpl中的requestLayout()方法,而它的方法做了线程检测如下图:这就是requestLayout()方法会崩溃的原因。

验证猜想:TextView设置跑马灯属性,使上面的if (mEllipsize != TextUtils.TruncateAt.MARQUEE)不成立,走下面的requestLayout()方法,代码如下:

 override fun onResume() {
        super.onResume()
        mBind.btTest.ellipsize = TextUtils.TruncateAt.valueOf("MARQUEE")
        mBind.btTest.setOnClickListener{
            lifecycleScope.launch(Dispatchers.IO) {
                mBind.btTest.text = "子线程点击改变:${Thread.currentThread().name}"
            }
        }
    }

果然点击后崩溃:

2.3、继续分析invalidate()方法,为什么不会导致textview的更新崩溃

看代码在View.java文件中

public void invalidate() {
    invalidate(true);
}

public void invalidate(boolean invalidateCache) {
    invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
}

void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
        boolean fullInvalidate) {
    if (mGhostView != null) {
        mGhostView.invalidate(true);
        return;
    }

    if (skipInvalidate()) {
        return;
    }

    // Reset content capture caches
    mPrivateFlags4 &= ~PFLAG4_CONTENT_CAPTURE_IMPORTANCE_MASK;
    mContentCaptureSessionCached = false;

    if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)
            || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID)
            || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED
            || (fullInvalidate && isOpaque() != mLastIsOpaque)) {
        if (fullInvalidate) {
            mLastIsOpaque = isOpaque();
            mPrivateFlags &= ~PFLAG_DRAWN;
        }

        mPrivateFlags |= PFLAG_DIRTY;

        if (invalidateCache) {
            mPrivateFlags |= PFLAG_INVALIDATED;
            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
        }

        // Propagate the damage rectangle to the parent view.
        final AttachInfo ai = mAttachInfo;
        final ViewParent p = mParent;
        if (p != null && ai != null && l < r && t < b) {
            final Rect damage = ai.mTmpInvalRect;
            damage.set(l, t, r, b);
            p.invalidateChild(this, damage);
        }

        // Damage the entire projection receiver, if necessary.
        if (mBackground != null && mBackground.isProjected()) {
            final View receiver = getProjectionReceiver();
            if (receiver != null) {
                receiver.damageInParent();
            }
        }
    }
}

核心代码是上面第三段invalidateInternal方法中的invalidateChild方法

它回调到ViewGroup中的invalidateChild方法

看:invalidateChild如下图:我们知道

if (attachInfo != null && attachInfo.mHardwareAccelerated) 条件成立attachInfo不为空 ,且硬件加速被开启(从API 14 (3.0)起。硬件加速默认开启)。 attachInfo 是一个view在attach至其父window被赋值的一系列信息。

所以条件成立后走的onDescendantInvalidated方法 如下:

@CallSuper
public void onDescendantInvalidated(@NonNull View child, @NonNull View target) {
    /*
     * HW-only, Rect-ignoring damage codepath
     *
     * We don't deal with rectangles here, since RenderThread native code computes damage for
     * everything drawn by HWUI (and SW layer / drawing cache doesn't keep track of damage area)
     */

    // if set, combine the animation flag into the parent
    mPrivateFlags |= (target.mPrivateFlags & PFLAG_DRAW_ANIMATION);

    if ((target.mPrivateFlags & ~PFLAG_DIRTY_MASK) != 0) {
        // We lazily use PFLAG_DIRTY, since computing opaque isn't worth the potential
        // optimization in provides in a DisplayList world.
        mPrivateFlags = (mPrivateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DIRTY;

        // simplified invalidateChildInParent behavior: clear cache validity to be safe...
        mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
    }

    // ... and mark inval if in software layer that needs to repaint (hw handled in native)
    if (mLayerType == LAYER_TYPE_SOFTWARE) {
        // Layered parents should be invalidated. Escalate to a full invalidate (and note that
        // we do this after consuming any relevant flags from the originating descendant)
        mPrivateFlags |= PFLAG_INVALIDATED | PFLAG_DIRTY;
        target = this;
    }

    if (mParent != null) {
        mParent.onDescendantInvalidated(this, target);
    }
}

上面一段代码核心是 mParent.onDescendantInvalidated(this, target); 类似于requestLayout()方法 onDescendantInvalidated中会循环递归调用 mParent.onDescendantInvalidated(this, target);方法,直到找到ViewRootImpl中的onDescendantInvalidated(this, target)方法,而它的方法没做线程检测如下图:这就是开了硬件加速后invalidate方法不会崩溃的原因。如下图:直接走scheduleTraversals绘制刷新有兴趣可看:

而关闭硬件加速后会怎样呢? 继续看invalidateChild方法

@Deprecated
@Override
public final void invalidateChild(View child, final Rect dirty) {
    final AttachInfo attachInfo = mAttachInfo;
    if (attachInfo != null && attachInfo.mHardwareAccelerated) {
        // HW accelerated fast path
        onDescendantInvalidated(child, child);
        return;
    }

    ViewParent parent = this;
    if (attachInfo != null) {
     
       ...

        do {
             ....
            parent = parent.invalidateChildInParent(location, dirty);
               
            ....
        } while (parent != null);
    }
}

上面一段核心是 parent = parent.invalidateChildInParent(location, dirty);方法 同理while循环不停调用 invalidateChildInParent方法直到找到ViewRootImpl中的invalidateChildInParent(int[] location, Rect dirty)方法,如下图内部进行了线程检测

**验证猜想关闭硬件加速:android:hardwareAccelerated="false"**果然崩溃了。

三、总结

这就是我遇到的问题:单纯的根据TextView在子线程可以更新得出的结论,总的来说要想不崩溃还得绕过ViewRootImpl中的checkThread的检测。至于研究它有什么用,只有知道理解源码的流程,才能写出更好的东西。

Android 学习笔录

Android 性能优化篇:https://qr18.cn/FVlo89
Android Framework底层原理篇:https://qr18.cn/AQpN4J
Android 车载篇:https://qr18.cn/F05ZCM
Android 逆向安全学习笔记:https://qr18.cn/CQ5TcL
Android 音视频篇:https://qr18.cn/Ei3VPD
Jetpack全家桶篇(内含Compose):https://qr18.cn/A0gajp
OkHttp 源码解析笔记:https://qr18.cn/Cw0pBD
Kotlin 篇:https://qr18.cn/CdjtAF
Gradle 篇:https://qr18.cn/DzrmMB
Flutter 篇:https://qr18.cn/DIvKma
Android 八大知识体:https://qr18.cn/CyxarU
Android 核心笔记:https://qr21.cn/CaZQLo
Android 往年面试题锦:https://qr18.cn/CKV8OZ
2023年最新Android 面试题集:https://qr18.cn/CgxrRy
Android 车载开发岗位面试习题:https://qr18.cn/FTlyCJ
音视频面试题锦:https://qr18.cn/AcV6Ap

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

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

相关文章

平凯星辰 TiDB 携手广发银行荣膺第十四届金融科技创新奖

近日&#xff0c;由《金融电子化》杂志社、苏州市金融科技协会共同主办的“第十四届金融科技创新奖颁奖典礼”在苏州隆重举行。 会上&#xff0c;由平凯星辰&#xff08;北京&#xff09;科技有限公司&#xff08;简称&#xff1a; 平凯星辰&#xff09;和广发银行共同申报的 “…

Java用Jsoup库实现的多线程爬虫代码

因为没有提供具体的Python多线程跑数据的内容&#xff0c;所以我们将假设你想要爬取的网站是一个简单的URL。以下是一个基本的Java爬虫程序&#xff0c;使用了Jsoup库来解析HTML和爬虫ip信息。 import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nod…

Vue 入门案例剖析

vscode 启用open with live server功能&#xff0c;配置谷歌浏览器chrome_小头猿的博客-CSDN博客 之所以使用vue就是想让其帮我们构建页面&#xff0c;构建出来了页面但是摆在那个位置呢&#xff1f;所以得准备好一个容器&#xff0c;最起码得有东西去承接这个界面。 控制台这…

谷歌插件报错 Manifest version 2 is deprecated, and support will be removed in 2023.

点开错误发现 高亮部分有问题。 下面是这个插件的解压后的原始包&#xff1a;我们主要就去找json结尾的东西 就这两个 一个个排除 找到了 把2 改成3就可以了 一定要记得保存&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff0…

大口径智能水表支持最高水流量是多少?

随着科技的不断发展&#xff0c;我国城市化进程的加快&#xff0c;水资源管理日益受到重视。作为一种先进的用水计量设备&#xff0c;大口径智能水表凭借其高精度、低误差、远程抄表等优点&#xff0c;在市场上备受青睐。那么接下来&#xff0c;小编就来为大家详细的介绍一下大…

Debian12换镜像源

0 背景 用docker运行了一个node容器&#xff0c;发现连vim也没有&#xff0c;所以打算安一个vim 1 查看操作系统 find / -name *release* #查看release信息2 更换镜像源 2.1 从网上找个国内镜像源 确定好操作系统版本后&#xff0c;从网上搜一下对应的数据源。这里提供一个…

全景房屋装修vr可视化编辑软件功能及特点

VR样板间、VR景观、VR商业街&#xff0c;全方位展示建筑内外空间使用及功能表現&#xff0c;让目标客戶能够身临其境体验項目的每处细节。 同时支持微信传播&#xff0c;线上看房&#xff0c;手机端VR沉浸式体验 3D互动售楼系统 3D互动售楼系统&#xff0c;集项目展示、智能选房…

C语言--汉诺塔【内容超级详细】

今天与大家分享一下如何用C语言解决汉诺塔问题。 目录 一.前言 二.找规律⭐ 三.总结⭐⭐⭐ 四.代码实现⭐⭐ 一.前言 有一部很好看的电影《猩球崛起》⭐&#xff0c;说呀&#xff0c;人类为了抗击癌症发明了一种药物&#x1f357;&#xff0c;然后给猩猩做了实验&#xff0…

js堆栈函数及断点调试(简单使用,仅供自己参考)

第一步打开调试面板点击源代码tab再点击webpack找到自己写的代码&#xff08;以vue项目为例&#xff0c;构建完后的项目是不能调试的&#xff09; 第二步在你需要调试的地方点击一下卡个点&#xff0c;如上图所示&#xff0c;然后刷新网页 第三步&#xff0c;点击调试操作箭头…

商人宝:新版收银系统比传统的收银机有哪些优势

新版收银系统凭借安装迅速、使用便捷、升级省心等特点&#xff0c;正逐步替换掉传统的安装下载的C/S架构的收银系统。今天&#xff0c;小编为大家分享新版收银系统对比传统收银机的三大优势。欢迎大家点赞关注&#xff0c;以及收藏本文章&#xff0c;以便后续多了解。 一是网页…

华为两大旗帜性人物相继发声!透露出哪些重要信息?

近几年&#xff0c;“算力”一词越来越频繁地出现在我们的视野中&#xff0c;随着数字化与智能化进程的加快&#xff0c;对于算力的要求越发迫切。 不知道朋友们有没有关注到&#xff0c;近日华为两大旗帜性人物&#xff0c;在短时间内也相继谈及算力...... 01 、华为持续加码…

这8个图片素材库,真的免费下载,4K无水印

不会还有人不知道去哪里下载高质量图片素材吧&#xff0c;给大家推荐8个网站&#xff0c;免费下载&#xff0c;以后的图片素材都不用愁了&#xff0c;赶紧收藏起来&#xff01; 1、菜鸟图库 https://www.sucai999.com/pic.html?vNTYxMjky 一个很大的素材库&#xff0c;站内主…

数字政府!3DCAT实时云渲染助推上海湾区数字孪生平台

数字孪生&#xff0c;是一种利用物理模型、传感器数据、运行历史等信息&#xff0c;在虚拟空间中构建实体对象或系统的精确映射&#xff0c;从而实现对其全生命周期的仿真、优化和管理的技术。数字孪生可以应用于各个领域&#xff0c;如工业制造、智慧城市、医疗健康、教育培训…

Linux-命令行命令

注&#xff1a;[]的内容说明是可选的 1.ls ls [-a -l -h] [Linux路径] >如果没有参数&#xff0c;就展示当前工作目录的内容 > -a&#xff1a;all的意思&#xff0c;即列出所有文件&#xff08;包含隐藏文件/文件夹&#xff09; > -l&#xff1a;以列表形式展示内容&…

怎么建模HEC-RAS【案例-利用HEC-RAS分析河道建筑对洪水管控的作用】 洪水计算、堤防及岸坡稳定计算、冲淤分析、壅水计算、冲刷计算、水工构筑物建模

背景介绍 人口数量的增长、不合理的区域规划和无计划的工程实践&#xff0c;让洪水对于人类而言变得极具风险。 为了最大程度地减少洪水造成的损害&#xff0c;采取管控措施往往需要在初期执行&#xff0c;为了研究这些管控措施&#xff0c;需要确定河段桥梁和作为调节的水利设…

基于springboot实现福聚苑社区团购平台系统项目【项目源码】计算机毕业设计

基于springboot实现福聚苑社区团购平台系统演示 Javar技术 Java是一种网络脚本语言&#xff0c;广泛运用于web应用开发&#xff0c;可以用来添加网页的格式动态效果&#xff0c;该语言不用进行预编译就直接运行&#xff0c;可以直接嵌入HTML语言中&#xff0c;写成js语言&…

畜牧猪舍养殖成功 管理效率提高的背后原因

畜牧养猪远程监控方案 畜牧养猪物联网远程监控方案其目的是为了提高养猪场的管理效率&#xff0c;降低生产成本&#xff0c;提高猪肉质量和养殖安全。现有的方案通常包括传感器和无线网络设备&#xff0c;这些设备可以监测养猪场的温度、湿度、气体浓度、环境光照等指标&#…

【bug】vue create 项目名,bash: vue: command not found

创建项目的时候&#xff0c;报bash: vue: command not found 一步一步排查 1、node是否安装&#xff0c;node -v 2、不是node的问题&#xff0c;试试npm install -g vue/cli&#xff0c;安装脚手架&#xff0c;其实这里是正在安装的意思&#xff0c;但是速度比较慢&#x…

物联网水表电子阀工作原理是怎样的?

随着科技的不断发展&#xff0c;物联网技术逐渐深入到我们的生活之中。作为智能家居的重要组成部分&#xff0c;物联网水表电子阀凭借其智能化、节能环保等优势&#xff0c;受到了越来越多用户的青睐。接下来&#xff0c;合众小编将来为大家介绍下物联网水表电子阀工作原理。 一…

载波通讯电表的使用年限是多久?

随着科技的飞速发展&#xff0c;智能家居、物联网等概念逐渐深入人心&#xff0c;载波通讯电表作为一种新型的智能电表&#xff0c;凭借其低功耗、高可靠性、远程通讯等优点&#xff0c;广泛应用于居民用电、工业生产等领域。那么&#xff0c;载波通讯电表的使用年限是多久呢&a…