class MyTimer extends CountDownTimer{
private static final String TAG = "HeartBeatTimer";
private static final long MILLIS_IN_FUTURE = 4000;
private static final long COUNT_DOWN_INTERVAL = 1000; // MILLIS_IN_FUTURE/2
public HeartBeatTimer(){
super(MILLIS_IN_FUTURE, COUNT_DOWN_INTERVAL);
}
@Override
public void onFinish() {
Log.d(TAG, "onFinish");
}
@Override
public void onTick(long millisUntilFinished) {
Log.d(TAG, "onTick" + millisUntilFinished);
}
}
android自己的sdk里面带了一个CountDownTimer, 可以用倒计时的方式处理一些问题.
09-19 17:07:30.098: DEBUG/HeartBeatTimer(29362): ON START
09-19 17:07:30.098: DEBUG/HeartBeatTimer(29362): onTick3996
09-19 17:07:31.098: DEBUG/HeartBeatTimer(29362): onTick2995
09-19 17:07:32.098: DEBUG/HeartBeatTimer(29362): onTick1994
09-19 17:07:34.098: DEBUG/HeartBeatTimer(29362): onFinish
我实验的时候, 出现了一个问题, 百思不得其解:
在这里例子里我设置定时时长为4s, 间隔时间为1s ;按道理应该每隔1s, 有一个ontick调用, 但最后一次ontick 和onFinish之间的间隔是2s.