CountDownTimer 實現倒計時功能

CountDownTimer

CountDownTimer 是android 自帶的一個倒計時類,使用這個類能夠很簡單的實現 倒計時功能android

CountDownTimer 的實現方式

new CountDownTimer(6000,1000) {//第一個參數表示的是倒計時的總時間,第二參數表示的是倒計時的間隔時間。
                    @Override
                    public void onTick(long millisUntilFinished) {//倒計時的過程
                        textView.setText(millisUntilFinished / 1000 + "秒");
                    }

                    @Override
                    public void onFinish() {//倒計時結束
                        textView.setText("倒計時結束");
                    }
                }.start();

實現效果ide

實現效果

取消計時器

調用 CountDownTimer 的 cancel() 方法,能夠爲咱們取消計時器:可是這個方法,只有在 android 5.0 以上纔有效果,在android 5.0 如下並無效果。若是須要在android 5.0 如下的系統中也使用 cancel,須要咱們本身根據 CountDownTimer 源碼中的 實現方式,從新實現一下。
cancel()源碼this

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


 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);
                }
            }
        }
    };

因爲在 android 5.0以上 增長了一個spa

private boolean mCancelled = false;

因此咱們只須要在 5.0 如下的系統中,去掉code

if (mCancelled) {
                    return;
                }

去掉這個判斷便可。blog

相關文章
相關標籤/搜索