android 倒计时工具类

Android 原声的CountDownTimer类存在计时不准有时候会跳转、不能到0秒的情况,而且时间是毫秒级,感觉用的不太习惯 ,所以根据CountDownTimer的源码自己修改为秒级的,而且可以倒计时到0秒,特记录下,只要在构造方法里传入倒计时秒数即可.

/**
 * @Date 2018/3/16  11:08
 * @TODO 倒计时工具类(秒)
 */
public abstract class CountTimeUtils {
        /**
         * Millis since epoch when alarm should stop.
         */
        private final long mMillisInFuture;

        private long mStopTimeInFuture;

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

        /**
         * @param secondInFuture The number of millis in the future from the call
         *   to {@link #start()} until the countdown is done and {@link #onFinish()}
         *   is called.
         */
        public CountTimeUtils(long secondInFuture) {
            mMillisInFuture = secondInFuture;
        }

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

        /**
         * Start the countdown.
         */
        public synchronized final CountTimeUtils start() {
            mCancelled = false;
            if (mMillisInFuture <= 0) {
                onFinish();
                return this;
            }
            mStopTimeInFuture = (SystemClock.elapsedRealtime()/1000) + 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 (CountTimeUtils.this) {
                    if (mCancelled) {
                        return;
                    }
                    final long millisLeft = mStopTimeInFuture - (SystemClock.elapsedRealtime()/1000);
                    if (millisLeft < 0) {
                        onFinish();
                    } else {
                        onTick(millisLeft);
                        sendMessageDelayed(obtainMessage(MSG), 1000);
                    }
                }
            }
        };
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凉亭下

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值