countdown timer plus_Android10使用

countdown timer plus_Android10使用AndroidCountDownTimer的使用

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

最近博主需要实现一个倒计时相关的功能,被推荐了Android的CountDownTimer工具类,在此说一下CountDownTimer的使用以及源码的解读

以下是一个总计10秒倒计时,每间隔1秒进行回调的例子:

        CountDownTimer timer = new CountDownTimer(10000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                // do something
            }

            @Override
            public void onFinish() {
                // do something
            }
        };
        timer.start();

每间隔1秒,CountDownTimer便会调用onTick回调方法执行相应操作

当倒计时结束后,CountDownTimer会调用onFinish回调方法执行相应的操作

看完CountDownTimer的例子后,我们可以看一下CountDownTimer的源码以加深对该工具类的理解,源码如下:

public abstract class CountDownTimer {

    /**
     * Millis since epoch when alarm should stop.
     */
    private final long mMillisInFuture;

    /**
     * The interval in millis that the user receives callbacks
     */
    private final long mCountdownInterval;

    private long mStopTimeInFuture;
    
    /**
    * boolean representing if the timer was cancelled
    */
    private boolean mCancelled = false;

    /**
     * @param millisInFuture The number of millis in the future from the call
     *   to {@link #start()} until the countdown is done and {@link #onFinish()}
     *   is called.
     * @param countDownInterval The interval along the way to receive
     *   {@link #onTick(long)} callbacks.
     */
    public CountDownTimer(long millisInFuture, long countDownInterval) {
        mMillisInFuture = millisInFuture;
        mCountdownInterval = countDownInterval;
    }

    /**
     * Cancel the countdown.
     */
    public synchronized final void cancel() {
        mCancelled = true;
        mHandler.removeMessages(MSG);
    }

    /**
     * Start the countdown.
     */
    public synchronized final CountDownTimer start() {
        mCancelled = false;
        if (mMillisInFuture <= 0) {
            onFinish();
            return this;
        }
        mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
        mHandler.sendMessage(mHandler.obtainMessage(MSG));
        return this;
    }


    /**
     * Callback fired on regular interval.
     * @param millisUntilFinished The amount of time until finished.
     */
    public abstract void onTick(long millisUntilFinished);

    /**
     * Callback fired when the time is up.
     */
    public abstract void onFinish();


    private static final int MSG = 1;


    // handles counting down
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            synchronized (CountDownTimer.this) {
                if (mCancelled) {
                    return;
                }

                final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();

                if (millisLeft <= 0) {
                    onFinish();
                } else {
                    long lastTickStart = SystemClock.elapsedRealtime();
                    onTick(millisLeft);

                    // take into account user's onTick taking time to execute
                    long lastTickDuration = SystemClock.elapsedRealtime() - lastTickStart;
                    long delay;

                    if (millisLeft < mCountdownInterval) {
                        // just delay until done
                        delay = millisLeft - lastTickDuration;

                        // special case: user's onTick took more than interval to
                        // complete, trigger onFinish without delay
                        if (delay < 0) delay = 0;
                    } else {
                        delay = mCountdownInterval - lastTickDuration;

                        // special case: user's onTick took more than interval to
                        // complete, skip to next interval
                        while (delay < 0) delay += mCountdownInterval;
                    }

                    sendMessageDelayed(obtainMessage(MSG), delay);
                }
            }
        }
    };
}

源码并不算长,CountDownTimer作为一个抽象类,其主要方法有如下几个:

  • start:开始进行倒计时
  • cancel:取消倒计时
  • onTick:抽象方法,用于倒计时间隔回调
  • onFinish:抽象方法,用于倒计时结束时回调
看过CountDownTimer的源码后,有几个细节我们需要稍微注意一下:
  1. 在源码第38行中,CountDownTimer会判断是否倒计时已结束,如果是则调用onFinish方法,否则调用onTick方法。因此,在倒计时的最后一秒时,我们并不会收到onTick的回调,取而代之的是onFinish的回调。
  2. 从源码可以看出,CountDownTimer其实与Timer完全没有任何关系,它的倒计时实现是使用Handler机制实现的,因此当我们在非UI线程使用该工具时,需要先初始化Looper
  3. 同上,由于CountDownTimer是基于Handler实现的,其处理以及发送message以及回调onTick处于同一线程,因此当我们在回调方法onTick耗时过多时,可能会影响CountDownTimer预估的回调次数(见源码144行)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/192397.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 教你PSD文件如何预览(支持32以及64位win7系统)

    教你PSD文件如何预览(支持32以及64位win7系统)相信随着软矿发出关于AdobeCS6的系列文章,很多矿友们已经按捺不住都早早的安装上了吧!但是笔者安装之后发现之前安装的PhotoshopCS5所具有的PSD文件预览功能消失了,相当郁闷的说~所以苦寻很多方法之后终于找到了消失的PSD文件预览功能。NO.1下载右侧链接的压缩包文件:点我下载下载完成后解压缩至任意目录,压缩包内容如下图所示然后将对应系统的MysticThum…

    2022年6月11日
    50
  • Quartz定时任务的组件API[通俗易懂]

    title:Quartz技术(二)-Quartz组件APIcategories:后端tags:定时任务本讲主要说明Quartz中重要的几个组件的API。Scheduler(调度器)Scheduler的生命期,从SchedulerFactory创建它时开始,到Scheduler调用shutdown()方法时结束;Scheduler被创建后,可以增加、删除和列举Job和Tri…

    2022年4月9日
    43
  • Android 的singleTask和singleInstance的一点思考[通俗易懂]

    Android 的singleTask和singleInstance的一点思考[通俗易懂]目录导语一、几个概念1、概念区分2、android:taskAffinity二、详细描述下这四种启动模式三、singleTask简单分析1、实例2、验证singleTask的几个特点3、简单总结singleTask的特点四、singleInstance的简单分析1、验证singleInstance的几个特点2、简单总结singleInstance的…

    2022年6月26日
    39
  • FM模型

    FM模型一、FM模型的意义1、传统模型的缺点忽略了特征之间的联系特征高维、稀疏,容易爆炸2、什么是FM模型FM就是FactorMachine,因子分解机。FM通过对两两特征组合,引入交叉项特征,提高模型得分;其次是高维灾难,通过引入隐向量(对参数矩阵进行矩阵分解),完成对特征的参数估计。二、FM模型1、对特征进行组合一般的线性模型y=ω0+∑i=1nwixiy={\om…

    2022年4月3日
    39
  • mysql 设置主键命令_MySQL常用命令

    mysql 设置主键命令_MySQL常用命令1、修改MySQL密码方法一:usemysql;updateusersetpassword=PASSWORD(“123456”)whereuser=‘root’;flushprivileges;忘记密码:sed-ri’3dskip-grant-tables’/etc/my.cnfsystemctlrestartmariadbusemysql;updateuse…

    2022年6月20日
    26
  • Java中的this关键字(三种用法)

    Java中的this关键字(三种用法)this关键字的三种用法:通过this关键字可以明确的访问一个类的成员变量,解决与局部变量名称冲突问题通过this关键字调用成员方法在构造方法中访问构造方法使用this([参数1,参数2,…])

    2022年6月16日
    29

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号