<p>获取短信验证码按钮的倒计时功能:</p><pre style="font-size: 9pt; font-family: 宋体; background-color: rgb(255, 255, 255);"><span style="background-color: rgb(228, 228, 255);">运用CountDownTimer</span>
写一个广告界面的倒计时,15s跳转到主界面。
mContentView = (TextView)findViewById(R.id.fullscreen_content);
new CountDownTimer(15000,1000) {
@Override
public void onTick(long millisUntilFinished) {
mContentView.setText(millisUntilFinished/1000 +"s");
}
@Override
public void onFinish() {
// mContentView.setText("DONE");
Intent it = new Intent(WelcomeActivity.this,LoginActivity.class);
WelcomeActivity.this.startActivity(it);
WelcomeActivity.this.finish();
}
}.start();
Button btok = (Button) findViewById(R.id.bt_ok);
new CountDownTimer(10000,1000){
@Override
public void onTick(long millisUntilFinished) {
btok.setText("剩余时间:"+ millisUntilFinished/1000+"");
}
@Override
public void onFinish() {
btok.setText("done");
}
}.start();
第一参数:总的倒计时间
第二参数:间隔时间
/** * @param millisInFuture The number of millis in the future from the call * to {@link #start()} until the countdown is done and {@link #onFinish()} * is called. * @param countDownInterval The interval along the way to receive * {@link #onTick(long)} callbacks. */ public CountDownTimer(long millisInFuture, long countDownInterval) { mMillisInFuture = millisInFuture; mCountdownInterval = countDownInterval; }
hander传递数据
// handles counting down
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
synchronized (CountDownTimer.this) {
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);
}
}
}
};
}