CountDownTimer使用

CountDownTimer使用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()方法。

今天的文章CountDownTimer使用分享到此就结束了,感谢您的阅读。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/23953.html

(0)
编程小号编程小号

相关推荐

发表回复

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