Timer的cancel问题

遇到有人问了个问题,关于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!建议多使用此种方法实现。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值