Android中的倒计时实现

Posted 寸草之心

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android中的倒计时实现相关的知识,希望对你有一定的参考价值。

一、android.os包下提供了倒计时的抽象工具类:

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 if (millisLeft < mCountdownInterval) {
                    // no tick, just delay until done
                    sendMessageDelayed(obtainMessage(MSG), millisLeft);
                } else {
                    long lastTickStart = SystemClock.elapsedRealtime();
                    onTick(millisLeft);
                    // take into account user‘s onTick taking time to execute
                    long delay = lastTickStart + mCountdownInterval - SystemClock.elapsedRealtime();
                    // special case: user‘s onTick took more than interval to
                    // complete, skip to next interval
                    while (delay < 0) delay += mCountdownInterval;
                    sendMessageDelayed(obtainMessage(MSG), delay);
                }
            }
        }
    };
}

 

二、一个Demo,用倒计时不断刷新剩余时间,倒计时结束后置button为可点击状态


private class TimeCount extends CountDownTimer {
    public TimeCount(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }
    /**
     * 计时过程中触发
     */
    @Override
    public void onTick(long millisUntilFinished) {
        if (mVerify != null) {
            int second = (int) (millisUntilFinished / 1000);  //计算出还剩多少秒
            mVerify.setText(getString(R.string.main_control_panel_grab_count_down, second));
         }
    }

    /**
     * 计时完成时触发
     */
    @Override
    public void onFinish() {
        isVerifing = false;
        if (mVerify != null) {
            mVerify.setEnabled(true);
            mVerify.setText(R.string.register_verify);
        }
    }
}

 




三、注意:

1. 该种方式实现的倒计时考虑了每次onTick处理函数中耗费的时间。
2. 使用的是handler机制,因此默认是靠Ui线程处理处理onTick函数(onTick中很可能有更新Ui的操作)
3. 可以看出,”循环“也是靠handleMessage方法中再抛一个Message方式实现(插一句话,常见的循环可以通过)。
4. 还有一点值得注意的是,每次onTick时,传入的是剩余时间值。
5. handleMessage方法的实现细节:
分两种情况:
1) onTick()的处理时间小于一个mCountdownInterval,所以delay(delay = lastTickStart + mCountdownInterval - SystemClock.elapsedRealtime())时间后正好是下一个onTick()时刻。
     

技术分享

2)  onTick()的处理时间大于或等于一个mCountdownInterval,不妨假设大于2个mCountdownInterval,则经过while循环不断跳过onTick()过程中耽搁的mCountdownInterval后,直到delay大于0时,正好是"下一个"mCountdownInterval后的onTick()时刻。

技术分享


以上是关于Android中的倒计时实现的主要内容,如果未能解决你的问题,请参考以下文章

android中的验证码倒计时

android 实现同时多个倒计时效果怎么做

Android游戏中的倒数计时器

Android开发:验证码倒计时功能实现

Android倒计时实现

Android实现计时与倒计时的几种方法