你的位置:首页 > 操作系统

[操作系统]安卓验证码倒计时实现


安卓为验证码倒计时提供了一个很方便的类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);        }      }    }  };

可以在以后做一些定时操作的时候,做相关的逻辑。