CountDownTimer使用

CountDownTimer

在做项目的时候,如果涉及到倒计时的功能的时候,都会使用到这个类,但是,常在河边走,哪有不湿身的。虽然经常使用,但是还是掉到了一次坑里面。

掉坑经历

背景

智能家居有这样一个需求,在设备成功配网以后,第一次初始化设备的shadow时比较耗时,所以要求15秒内,每3秒请求一次,有一次成功,则完成设备的初始化。

解决方案

15秒内,所以使用到了countDownTimer做倒计时;
每3秒请求一次,则使用Timer和TimerTask;
timerTask每三秒执行一次请求shadow状态的Topic,有一次成功获取到shadow的正确状态,则关闭countDownTimer、timer、timerTask;

掉坑

关闭countDownTimer,调用了cancel();
关闭timer,调用了cancel();
关闭timerTask,调用了cancel();
坑就在这系列cancel(),countDownTimer的onFinish()回调里关闭timer和timerTask。

弃坑

背景

15秒内成功请求到了shadow的正确状态,但是timerTask还在一直执行,什么鬼,不是全部cancel()了吗?

解决方案

然后就一路debug,突然发现,执行countDownTimer的cancel()方法后,并没有调用onFinish(),纳尼,这是什么情况?
进入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;
        //总时长小于等于0,则调用onFinish()
        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);
                }
            }
        }
    };
}

cancel()方法

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

发现并没有调用onFinish()方法,只是发送了移除message的信息。所以,调用cancel()方法并不会调用onFinish()方法,只是调用handler的removeMessages()方法。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值