Android 自定义view优化方案

最近公司来了一个新的需求:将一些机车参数在app端用进度、动画的效果显示出来,于是在网上找了一大堆自定义View实现的进度条代码,最终搞出来了。界面中有四个控件是通过自定义view实现的,数据接收的频率是500ms一条数据,收到数据之后使用handler更新到UI线程直接显示数据。但是遇到一个问题,当绘制的时间比较长时,大约超过半个小时左右界面上的数值变化就会明显变慢,出现界面延迟伴有卡顿的情况。于是最近这几天一点点慢慢的优化,效果才有明显好转。接下来我来讲讲我具体优化了哪些方面的东西。

一、绘制onDraw()的优化

在每次数据更新之后,都会调用一次invalidate()或者postInvalidate()来更新UI,让onDraw()进行重新绘制。所以在onDraw()中不要创建新的局部对象。onDraw()方法执行的频率比较高,这样就会在一瞬间产生大量的临时对象,这不仅占用了过多的内存,而且还会导致系统更加频繁gc,降低了程序的执行效率。

原先的代码:

每次执行onDraw都会创建一个Matrix对象。

    @Override
    protected void onDraw(Canvas canvas) {
       Matrix mDynamicMatrix = new Matrix();
       mDynamicMatrix.setRotate(startAngele, canvas.getWidth() / 2, canvas.getHeight() / 2);
       mDynamicShader.setLocalMatrix(mDynamicMatrix);
       mPaint.setShader(mDynamicShader);
    }

优化后的代码:

进行非空判断,Matrix只创建一次。

    private Matrix mDynamicMatrix = null;
    @Override
    protected void onDraw(Canvas canvas) {
       if (mDynamicMatrix == null) {
           mDynamicMatrix = new Matrix();
       }
       mDynamicMatrix.setRotate(startAngele, canvas.getWidth() / 2, canvas.getHeight() / 2);
       mDynamicShader.setLocalMatrix(mDynamicMatrix);
       mPaint.setShader(mDynamicShader);
    }

总言之,在onDraw()中尽量避免对象的重复创建

二、动画的优化

原先的代码:

ValueAnimator.ofFloat()会多次创建ValueAnimator对象。

    private void startAnimator(float start, float end, long animTime) {
        mAnimator = ValueAnimator.ofFloat(start, end);
        mAnimator.setDuration(animTime);
        mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mPercent = (float) animation.getAnimatedValue();
                mValue = mPercent * mMaxValue;
              
                invalidate();
            }
        });
        mAnimator.start();
    }

优化后的代码:

初始化的时候创建ValueAnimator,然后在使用的时候通过setFloatValues()赋值。

    //初始化的时候创建ValueAnimator,注册监听
    private void initAnim() {
        mAnimator = new ValueAnimator();
        mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mPercent = (float) animation.getAnimatedValue();
                mValue = mPercent * mMaxValue;
                invalidate();
            }
        });
    }

    private void startAnimator(float start, float end, long animTime) {
        mAnimator.setFloatValues(start, end);
        mAnimator.setDuration(animTime);
        mAnimator.start();
    }

原理是避免对象的重复创建

查看ValueAnimator.ofFloat(start, end)的源码:

    /**
     * Constructs and returns a ValueAnimator that animates between float values. A single
     * value implies that that value is the one being animated to. However, this is not typically
     * useful in a ValueAnimator object because there is no way for the object to determine the
     * starting value for the animation (unlike ObjectAnimator, which can derive that value
     * from the target object and property being animated). Therefore, there should typically
     * be two or more values.
     *
     * @param values A set of values that the animation will animate between over time.
     * @return A ValueAnimator object that is set up to animate between the given values.
     */
    public static ValueAnimator ofFloat(float... values) {
        ValueAnimator anim = new ValueAnimator();
        anim.setFloatValues(values);
        return anim;
    }

可以看出ofFloat()每执行一次,会创建一个ValueAnimator()对象。在初始化的时候创建一次ValueAnimator对象,更新数据直接使用ValueAnimator的setFloatValues()方法进行数据更新,可以避免ValueAnimator对象的重复创建。

三、invalidate()方法的执行时机

原先的代码:

onAnimationUpdate()监听1秒执行6次、4次、3次,次数不等,invalidate()方法也执行了多次,多次无必要的绘制造成大量资源的浪费。

    //初始化的时候创建ValueAnimator,注册监听
    private void initAnim() {
        mAnimator = new ValueAnimator();
        mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mPercent = (float) animation.getAnimatedValue();
                mValue = mPercent * mMaxValue;
                invalidate();
            }
        });
    }
    //启动动画
    private void startAnimator(float start, float end, long animTime) {
        mAnimator.setFloatValues(start, end);
        mAnimator.setDuration(animTime);
        mAnimator.start();
    }

优化之后:

增加一个动画开始、结束的监听,把invalidate()放到动画结束之后onAnimationEnd()方法中执行。前面提到数据接收的频率是500ms一条数据,动画的时间我这里设置的1,也就是1ms,可以忽略不计。1秒内动画执行两次,打印出来正好是执行了两次invalidate()。

    //初始化的时候创建ValueAnimator,注册监听
    private void initAnim() {
        mAnimator = new ValueAnimator();
        mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mPercent = (float) animation.getAnimatedValue();
                mValue = mPercent * mMaxValue;
               
            }
        });
        mAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                invalidate();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }

invalidate()每执行一次,onDraw()方法就会跟着执行一次,重绘ui会占用较多的内存。为了避免资源的浪费,我们应该尽量减少invalidate()方法的调用频率

四、invalidate和postInvalidate的区别

自定义view中实现view的更新有两种方式,一种是invalidate(),另一种是postInvalidate()。

invalidate()是在UI线程中使用,而postInvalidate()是在非UI线程中使用。

1、invalidate()

看一下invalidate()的源码:

    /**
     * Invalidate the whole view. If the view is visible,
     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
     * the future.
     * <p>
     * This must be called from a UI thread. To call from a non-UI thread, call
     * {@link #postInvalidate()}.
     */
    public void invalidate() {
        invalidate(true);
    }

  从方法中的注释中看,我们知道invalidate方法会刷新整个View,并且当这个View的可见性为VISIBLE的时候,View的onDraw()方法将会被调用。另外注意的是这个方法只能在UI线程中去调用。

上面就能够基本知道invalidate方法是干什么的了。我们往下接着看源码:

    /**
     * This is where the invalidate() work actually happens. A full invalidate()
     * causes the drawing cache to be invalidated, but this function can be
     * called with invalidateCache set to false to skip that invalidation step
     * for cases that do not need it (for example, a component that remains at
     * the same dimensions with the same content).
     *
     * @param invalidateCache Whether the drawing cache for this view should be
     *            invalidated as well. This is usually true for a full
     *            invalidate, but may be set to false if the View's contents or
     *            dimensions have not changed.
     * @hide
     */
    @UnsupportedAppUsage
    public void invalidate(boolean invalidateCache) {
        invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
    }

我们看到,invalidate()方法中是调用invalidate(true),参数true的意思是需要整体刷新,当View的内容和大小没有任何变化时我们可以传入false。

2、postInvalidate()

接下来看下postInvalidate()的实现:

    /**
     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
     * Use this to invalidate the View from a non-UI thread.</p>
     *
     * <p>This method can be invoked from outside of the UI thread
     * only when this View is attached to a window.</p>
     *
     * @see #invalidate()
     * @see #postInvalidateDelayed(long)
     */
    public void postInvalidate() {
        postInvalidateDelayed(0);
    }
    /**
     * <p>Cause an invalidate to happen on a subsequent cycle through the event
     * loop. Waits for the specified amount of time.</p>
     *
     * <p>This method can be invoked from outside of the UI thread
     * only when this View is attached to a window.</p>
     *
     * @param delayMilliseconds the duration in milliseconds to delay the
     *         invalidation by
     *
     * @see #invalidate()
     * @see #postInvalidate()
     */
    public void postInvalidateDelayed(long delayMilliseconds) {
        // We try only with the AttachInfo because there's no point in invalidating
        // if we are not attached to our window
        final AttachInfo attachInfo = mAttachInfo;
        if (attachInfo != null) {
            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
        }
    }
    /**
     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
     * through the event loop. Waits for the specified amount of time.</p>
     *
     * <p>This method can be invoked from outside of the UI thread
     * only when this View is attached to a window.</p>
     *
     * @param delayMilliseconds the duration in milliseconds to delay the
     *         invalidation by
     * @param left The left coordinate of the rectangle to invalidate.
     * @param top The top coordinate of the rectangle to invalidate.
     * @param right The right coordinate of the rectangle to invalidate.
     * @param bottom The bottom coordinate of the rectangle to invalidate.
     *
     * @see #invalidate(int, int, int, int)
     * @see #invalidate(Rect)
     * @see #postInvalidate(int, int, int, int)
     */
    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
            int right, int bottom) {
        // We try only with the AttachInfo because there's no point in invalidating
        // if we are not attached to our window
        final AttachInfo attachInfo = mAttachInfo;
        if (attachInfo != null) {
            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
            info.target = this;
            info.left = left;
            info.top = top;
            info.right = right;
            info.bottom = bottom;
            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
        }
    }

从上面的方法注释中可以知道,postInvalidate是可以在非UI线程中去调用刷新UI的,那是如何做到的呢?从上面的方法调用栈中可以看出来,调用postInvalidate方法最后会调用View中的mHander发送一个MSG_INVALIDATE的消息。mHandler是ViewRootHandler的一个实例,从ViewRootHandler的handleMessage()方法中一探究竟(方法较长,只截取部分):

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_INVALIDATE:
                    ((View) msg.obj).invalidate();
                    break;
                case MSG_INVALIDATE_RECT:
                    final View.AttachInfo.InvalidateInfo info =
                            (View.AttachInfo.InvalidateInfo) msg.obj;
                    info.target.invalidate(info.left, info.top, info.right, info.bottom);
                    info.recycle();
                    break;
                case MSG_PROCESS_INPUT_EVENTS:
                    mProcessInputEventsScheduled = false;
                    doProcessInputEvents();
                    break;

在Handler中最后还是会调用View的invalidate()方法去刷新,只不过postInvalidate()方法是通过Handler将刷新事件通知发到Handler的handlerMessage中去执行invalidate的。

"invalidate和postInvalidate的区别" 出处:https://cloud.tencent.com/developer/article/1355393

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

python学习——【第六弹】

前言 上一篇文章 python学习——【第五弹】中我们了解了python中的不可变序列元组&#xff0c;这篇文章接着介绍可变序列 字典。 字典 字典的实现原理&#xff1a; 字典&#xff0c;顾名思义其实现原理和字典类似&#xff0c;字典中的元素都是key—value&#xff0c;以键值对…

操作系统学习笔记 ---- 网络系统

1 DMA技术 直接内存访问&#xff08;Direct Memory Access&#xff09; 技术。 在进行 I/O 设备和内存的数据传输的时候&#xff0c;数据搬运的工作全部交给 DMA 控制器&#xff0c;而 CPU 不再参与任何与数据搬运相关的事情&#xff0c;这样 CPU 就可以去处理别的事务。 DM…

js逆向学习、安卓逆向

JS基础 提示信息 - 吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn 安卓逆向 1.模拟器环境搭建 Magisk 是一套用于定制 Android 的开源软件&#xff0c;支持高于 Android 5.0 的设备。 以下是一些功能亮点&#xff1a; MagiskSU&#xff1a;为应用程序提供 root 访…

什么是 .com 域名?含义和用途又是什么?

随着网络的发展&#xff0c;网络上出现了各种不同后缀的域名&#xff0c;这些域名的后缀各有不同的含义&#xff0c;也有不同的用途。今天&#xff0c;我们就一起来探讨一下 .com 后缀的域名知识。 .com 域名是一种最常见的顶级域名&#xff0c;它是由美国国家网络信息中心&…

第3章 多层感知器

这章节我们来解决的问题是&#xff1a;如何使用神经网络实现逻辑电路中的“异或门”模型&#xff1f;如下图&#xff1a;根据第2章我们知道&#xff0c;单层感知器是能够解决“与门”、“或门”、“非门”这些简单的线性问题&#xff0c;但是不能解决“异或门”这类非线性问题。…

内存函数的简单实用

本篇要分享的是常见的内存函数 前面分享的函数都是和字符串相关&#xff0c;但是当我们在操作数据的时候不仅仅要操作字符数据 接下来分享几个与内存相关的函数 目录 本篇要分享的是常见的内存函数 1.memcpy 2.memmove 自定函数模拟实现memmove函数 3.memcmp 4.memset …

【算法经典题集】DP和枚举(持续更新~~~)

&#x1f63d;PREFACE&#x1f381;欢迎各位→点赞&#x1f44d; 收藏⭐ 评论&#x1f4dd;&#x1f4e2;系列专栏&#xff1a;算法经典题集&#x1f50a;本专栏涉及到的知识点或者题目是算法专栏的补充与应用&#x1f4aa;种一棵树最好是十年前其次是现在DPDP就是动态规划&a…

Web前端 JS WebAPI

1、操作DOM 1.1、什么DOM&#xff1f; DOM&#xff08;Document Object Model——文档对象模型&#xff09;&#xff1a;DOM是浏览器提供的一套专门用来操作网页内容的功能 DOM作用&#xff1a;开发网页内容特效和实现用户交互 DOM树是什么&#xff1f; 将 HTML 文档以树状…

手把手教你使用vue创建第一个vis.js

先看一下实现效果吧 &#xff0c;如下图 &#xff1a; 为什么要写这篇文章呢&#xff1f;因为之前有浅浅的了解一下vis.js&#xff0c;后期开发中没有使用vis&#xff0c;所以太深奥的也不懂&#xff0c;但是当时是用js写的。这两天有人问我用vue怎么写&#xff0c;然后说看到…

减治法实现插入排序,减治法实现二叉查找树(二叉搜索数,二叉排序数)的创建、插入与查找(含解析与代码实现)

&#x1f38a;【数据结构与算法】专题正在持续更新中&#xff0c;各种数据结构的创建原理与运用✨&#xff0c;经典算法的解析✨都在这儿&#xff0c;欢迎大家前往订阅本专题&#xff0c;获取更多详细信息哦&#x1f38f;&#x1f38f;&#x1f38f; &#x1fa94;本系列专栏 -…

嵌入式软件开发之Linux下C编程

目录 前沿 Hello World&#xff01; 编写代码 编译代码 GCC编译器 gcc 命令 编译错误警告 编译流程 Makefile 基础 何为 Makefile Makefile 的引入 前沿 在 Windows 下我们可以使用各种各样的 IDE 进行编程&#xff0c;比如强大的 Visual Studio。但是在Ubuntu 下如何进…

【Java版oj】day10 井字棋、密码强度等级

目录 一、井字棋 &#xff08;1&#xff09;原题再现 &#xff08;2&#xff09;问题分析 &#xff08;3&#xff09;完整代码 二、密码强度等级 &#xff08;1&#xff09;原题再现 &#xff08;2&#xff09;问题分析 &#xff08;3&#xff09;完整代码 一、井字棋 &a…

CAT8网线测试仪使用中:线缆的抗干扰参数解读以及线缆工艺改进注意事项

FLUKE Agent platform -深圳维信&#xff0c;带你更深入的了解铜缆测试&#xff0c;详细为您讲解什么是TCL/ELTCL&#xff0c;他们对数据的传输到底有什么影响呢&#xff1f; 前情分析&#xff1a;为什么用双绞线传输信号&#xff1f;&#xff08;一图就懂&#xff09; TCL&a…

【深度解刨C语言】符号篇(全)

文章目录一.注释二.续行符与转义符1.续行符2.转义符三.回车与换行四.逻辑操作符五.位操作符和移位操作符六.前置与后置七.字符与字符串八./和%1.四种取整方式2.取模与取余的区别和联系3./两边异号的情况1.左正右负2.左负右正九.运算符的优先级一.注释 注释的两种符号&#xff…

Sentinel

SentinelSentinel介绍什么是Sentinel?为什么需要流量控制&#xff1f;为什么需要熔断降级&#xff1f;一些普遍的使用场景本文介绍参考&#xff1a;Sentinel官网《Spring Cloud Alibaba 从入门到实战.pdf》Sentinel下载/安装项目演示构建项目控制台概览演示之前需先明确&#…

【webrtc】ICE 到VCMPacket的视频内存分配

ice的数据会在DataPacket 构造是进行内存分配和拷贝而后DataPacket 会传递给rtc模块处理rtc模块使用DataPacket 构造rtp包最终会给到OnReceivedPayloadData 进行rtp组帧。吊炸天的是DataPacket 竟然没有声明析构方法。RtpVideoStreamReceiver::OnReceivedPayloadData 的内存是外…

3.网络爬虫——Requests模块get请求与实战

Requests模块get请求与实战requests简介&#xff1a;检查数据请求数据保存数据前言&#xff1a; 前两章我们介绍了爬虫和HTML的组成&#xff0c;方便我们后续爬虫学习&#xff0c;今天就教大家怎么去爬取一个网站的源代码&#xff08;后面学习中就能从源码中找到我们想要的数据…

普通Java工程师 VS 优秀架构师

1 核心能力 1.1 要成为一名优秀的Java架构师 只懂技术还远远不够&#xff0c;懂技术/懂业务/懂管理的综合型人才&#xff0c;才是技术团队中的绝对核心。 不仅仅是架构师&#xff0c;所有的技术高端岗位&#xff0c;对人才的综合能力都有较高的标准。 架构路线的总设计师 规…

安卓渐变的背景框实现

安卓渐变的背景框实现1.背景实现方法1.利用PorterDuffXfermode进行图层的混合&#xff0c;这是最推荐的方法&#xff0c;也是最有效的。2.利用canvas裁剪实现&#xff0c;这个方法有个缺陷&#xff0c;就是圆角会出现毛边&#xff0c;也就是锯齿。3.利用layer绘制边框1.背景 万…

多线程案例——阻塞队列

目录 一、阻塞队列 1. 生产者消费者模型 &#xff08;1&#xff09;解耦合 &#xff08;2&#xff09;“削峰填谷” 2. 标准库中的阻塞队列 3. 自己实现一个阻塞队列&#xff08;代码&#xff09; 4. 自己实现生产者消费者模型&#xff08;代码&#xff09; 一、阻塞队列…
最新文章