最近在项目中需要在TextView中显示一个倒计时的功能,主要用到CountDownTimer抽象类。
使用该类需要给定两个时间,构造方法为:
public CountDownTimer(long millisInFuture, long countDownInterval){}
millisInFuture:该变量表示从调用start()方法开始,到onFinish()方法被回调共倒计时多少时间。
countDownInterval:时间间隔。
这两个变量的单位都是毫秒。
通过调用start()方法开始倒计时,源码如下:
public synchronized final CountDownTimer start() {
mCancelled = false;
if (mMillisInFuture <= 0) {
onFinish();
return this;
}
mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
mHandler.sendMessage(mHandler.obtainMessage(MSG));
return this;
}
从源码中可看到是通过Handler来发送消息。
通过调用cancel()方法结束倒计时,源码如下:
public synchronized final void cancel() {
mCancelled = true;
mHandler.removeMessages(MSG);
}
通过Handler将消息从消息队列中移除。
其实CountDownTimer只是对Handler进行了封装,追根究底还是使用了异步消息处理机制。
我们可自定义类继承CountDownTimer类,实现onTick()和onFinish()方法来实现在倒计时过程中对UI的操作。如:
private class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
mSendCaptcha.setText("(" + millisUntilFinished / 1000 + "s)" );
setSendButton(false);
}
@Override
public void onFinish() {
mSendCaptcha.setText(R.string.regain_captch_text);
setSendButton(true);
}
}