Windows风格的Loading动画Android实现(2)

为了防止ANR,博客介绍了如何在Android中使用HandlerThread和Handler在工作线程进行计算,而在UI线程更新加载动画。通过创建HandlerThread、workerHandler和uiHandler,实现在工作线程计算参数,UI线程执行绘制,从而实现高效且流畅的Loading动画效果。
摘要由CSDN通过智能技术生成

前言

众所周知,为了不ANR,不可以在UI线程上执行耗时的操作。所以为了效率,也为了通用,我把计算绘制参数的操作放到工作线程中去了。参考了这篇文章

首先创建一个工作线程(workerThread),一个与workerThread关联的Handler(workerHandler),还有一个和UI线程关联的Handler(uiHandler)。在onDraw()执行结束之后,会通过workerHander发消息,workerThread收到消息会去重新计算绘制参数。完成之后,会通过uiHandler发消息,UI线程收到消息之后调用invalidate(),会导致onDraw()被执行。进入下一次循环。

这样就实现了,重新计算绘制参数在workerThread执行,invalidate()在UI线程执行。在这里,handler充当信使的作用,它可以在其他线程向自己关联的线程发消息、post runnable等等。

HandlerThread知识

HandlerThread类的注释:

Handy class for starting a new thread that has a looper. The looper can then be  used to create handler classes. Note that start() must still be called.

Handler类的注释

/**
* A Handler allows you to send and process {@link Message} and Runnable
* objects associated with a thread's {@link MessageQueue}.  Each Handler
* instance is associated with a single thread and that thread's message
* queue.  When you create a new Handler, it is bound to the thread /
* message queue of the thread that is creating it -- from that point on,
* it will deliver messages and runnables to that message queue and execute
* them as they come out of the message queue.
* 
 * <p>There are two main uses for a Handler: (1) to schedule messages and
* runnables to be executed as some point in the future; and (2) to enqueue
* an action to be performed on a different thread than your own.......

源码

public class LoadingView extends View {
   

    /**
     * A list that contains the cx of each point.
     */
    private List<Float> cx;

    /**
     * The cy of every point is the same.
     */
    private float cy;

    /**
     * The radius of every point is the same.
     */
    private float radius;

    /**
     * The paints that used to draw each point.
     */
    private List<Paint> paints;

    /**
     * The length that point transfer to en
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值