遇到有人问了个问题,关于Timer的,在这里记一下。
Timer在调用cancel之后不会立马去停止,它不会干扰正在执行的任务,计时器终止的话,当前的任务将是最后一次的调用,cancel可以多次调用,第一次的调用之后是没有作用的,源码中的解释如下:
Terminates this timer, discarding any currently scheduled tasks.
* Does not interfere with a currently executing task (if it exists).
* Once a timer has been terminated, its execution thread terminates
* gracefully, and no more tasks may be scheduled on it.
*
* Note that calling this method from within the run method of a
* timer task that was invoked by this timer absolutely guarantees that
* the ongoing task execution is the last task execution that will ever
* be performed by this timer.
*
* This method may be called repeatedly; the second and subsequent
* calls have no effect.
如果细心一点,我们会发现,Timer是java.util中的类,而在android中也提供了这种使用方式,那就是倒计时类CountDownTimer,更加符合android的环境,推荐使用。下面是它的使用实例:
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
上面表示的从30s开始以没秒为单位倒计时,其中mTextField上显示剩余的时间,当时间为0时,调用onFinish方法,mTextField上done!建议多使用此种方法实现。