Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> 安卓驗證碼倒計時實現,安卓驗證碼倒計時

安卓驗證碼倒計時實現,安卓驗證碼倒計時

編輯:關於android開發

安卓驗證碼倒計時實現,安卓驗證碼倒計時


安卓為驗證碼倒計時提供了一個很方便的類android.os.CountDownTimer

其使用方法:


new CountDownTimer(30000, 1000) {

     public void onTick(long millisUntilFinished) {
          mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     }
 
    public void onFinish() {
         mTextField.setText("done!");
      }
  }.start();

onTick 間隔時間回調 onfinish 倒計時完回調

從源碼可以看到其實現主要是通過sendMessageDelayed實現的,其主要的邏輯如下:

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

可以在以後做一些定時操作的時候,做相關的邏輯。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved