【问题标题】:CountDownTimer.cancel() is not working in AndroidCountDownTimer.cancel() 在 Android 中不起作用
【发布时间】:2011-09-19 09:53:53
【问题描述】:

CountDownTimer.cancel() 在以下代码中不起作用:

myTimer = new CountDownTimer(10000, 1000) {
    public void onFinish() {
    }
    @Override
    public void onTick(long millisUntilFinished) {
        if(null != myObject){
            myTimer.cancel();
        }
    }
}.start();

在上面的代码中,我启动了一个CountDownTimer,它检查对象是否不是null,并相应地取消定时器。该对象由某个侦听器在任何时间点设置。 请参考和建议。我在这里做对了吗?

Gautier Hayoun 的解决方案

刚刚做了一个替换 可以取消的 CountDownTimer 从 onTick 内部:Github link– Gautier Hayoun 2010 年 12 月 12 日 1:04

【问题讨论】:

  • 问题可能是您在新创建的对象内引用myTimer。试试this.cancel(); 而不是myTimer.cancel();
  • 这是 Android 错误吗?为此,我真的很沮丧。

标签: java android timer


【解决方案1】:

Gautier Hayoun 的解决方案:

刚刚替换了 CountDownTimer,您可以从 onTick 中取消:Github link– Gautier Hayoun 2010 年 12 月 12 日 1:04

【讨论】:

【解决方案2】:

使用TimerTask代替CountDownTimer

final static long INTERVAL=1000;
final static long TIMEOUT=10000;


TimerTask task=new TimerTask(){
            @Override
            public void run() {
                elapsed+=INTERVAL;
                if(elapsed>=TIMEOUT){
                    this.cancel();
                    displayText("finished");
                    return;
                }
                //if(some other conditions)
                //   this.cancel();
                displayText("seconds elapsed: " + elapsed / 1000);
            }
        };
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, INTERVAL, INTERVAL);

private void displayText(final String text){
    this.runOnUiThread(new Runnable(){
        @Override
        public void run() {
            mTextField.setText(text);
        }
    });
}

【讨论】:

  • 倒计时的探针是什么?
  • CountDown 有一些取消的问题,通常如果你调用 cancel() 它不会被停止,你将有 2 个定时器同时工作
猜你喜欢
  • 1970-01-01
  • 2018-06-18
  • 2021-08-31
  • 2016-02-20
  • 2015-05-25
  • 2012-12-26
  • 2017-02-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多