安卓為驗證碼倒計時提供了一個很方便的類android.os.CountDownTimer 其使用方法:new CountDownTimer(30000, 1000) { public void onTick(long millisUntilFinished) { mTextField.setText... ...
安卓為驗證碼倒計時提供了一個很方便的類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); } } } };
可以在以後做一些定時操作的時候,做相關的邏輯。