CountDownTimer 这个搞 Android 开发的同学,一定不陌生。
在android.os
包下面的一个抽象类。
部分核心源码:
// handles counting down
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);
}
}
}
};
查看源码可以发现,其实现 是通过 Handler + Message ,呃,那就没什么好说的了。
具体实现示例:
private CountDownTimer countDownTimer;
private void startTimerTask() {
if (countDownTimer == null) {
countDownTimer = new CountDownTimer(10000000, 5000) {
@Override
public void onTick(long millisUntilFinished) {
//todo timer Task
}
@Override
public void onFinish() {
}
};
}
countDownTimer.start();
}
private void stopTimerTask() {
if (countDownTimer != null) {
countDownTimer.cancel();
countDownTimer = null;
}
}
每隔5秒执行一次操作,共执行 10000000/5000
次。