溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Android CountDownTimer實(shí)現(xiàn)倒計(jì)時(shí)器

發(fā)布時(shí)間:2020-09-27 00:55:41 來(lái)源:腳本之家 閱讀:157 作者:銀色子彈 欄目:移動(dòng)開發(fā)

使用介紹

開發(fā)中經(jīng)常會(huì)遇到一些和倒計(jì)時(shí)有關(guān)的場(chǎng)景,比如發(fā)送驗(yàn)證碼的按鈕,會(huì)在點(diǎn)擊發(fā)送后,顯示倒計(jì)時(shí)間,倒計(jì)時(shí)結(jié)束后才能夠刷新按鈕,再次允許點(diǎn)擊。為了不阻塞軟件的運(yùn)行,又要實(shí)時(shí)刷新界面,我們通常會(huì)用到 Handler 或者 AsyncTask 等技術(shù),自己寫邏輯實(shí)現(xiàn)。其實(shí) Android 中已經(jīng)封裝好了一套 CountDownTimer 來(lái)實(shí)現(xiàn)這個(gè)功能需求。

CountDownTimer(long millisInFuture, long countDownInterval)

CountDownTimer的兩個(gè)參數(shù)分別表示倒計(jì)時(shí)的總時(shí)間 millisInFuture 和間隔時(shí)間 countDownInterval。

具體的調(diào)用如下:

TextView vertifyBtn;
CountDownTimer timer = new CountDownTimer(60000, 1000) {

  @Override
  public void onTick(long millisUntilFinished) {
    vertifyBtn.setText((millisUntilFinished / 1000) + " second");
  }
  
  @Override
  public void onFinish() {
    vertifyBtn.setEnabled(true);
    vertifyBtn.setText("Send");
  }
};
timer.start();

上面的調(diào)用舉例表示總計(jì) 60 秒,每 1 秒都會(huì)執(zhí)行一次 onTick 方法,其參數(shù) millisUntilFinished 表示倒計(jì)時(shí)剩余時(shí)間毫秒數(shù),最后倒計(jì)時(shí)結(jié)束執(zhí)行 onFinish 方法。

實(shí)現(xiàn)原理

下面是 CountDownTimer 的源碼,代碼非常少,很好理解。從源代碼中可以看出,其實(shí) CountDownTimer 也是利用 Handler 的消息處理機(jī)制來(lái)實(shí)現(xiàn)效果的。初始化設(shè)定好起始和終止時(shí)間后,每隔一定的間隔時(shí)間通過(guò) Handler 給主線程發(fā)送消息,然后再在消息處理中回調(diào)方法。好好利用官方封裝好的工具類,可以避免我們重復(fù)的造輪子,當(dāng)然了解輪子的原理就更好了!

package android.os;

public abstract class CountDownTimer {
  private final long mMillisInFuture;
  private final long mCountdownInterval;
  private long mStopTimeInFuture;
  private boolean mCancelled = false;

  public CountDownTimer(long millisInFuture, long countDownInterval) {
    mMillisInFuture = millisInFuture;
    mCountdownInterval = countDownInterval;
  }

  public synchronized final void cancel() {
    mCancelled = true;
    mHandler.removeMessages(MSG);
  }

  public synchronized final CountDownTimer start() {
    mCancelled = false;
    if (mMillisInFuture <= 0) {
      onFinish();
      return this;
    }
    mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
    mHandler.sendMessage(mHandler.obtainMessage(MSG));
    return this;
  }

  public abstract void onTick(long millisUntilFinished);

  public abstract void onFinish();

  private static final int MSG = 1;
  
  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);
        }
      }
    }
  };
}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI