当我调用cancel时,timer.scheduleAtFixedRate不会停止

时间:2013-01-10 07:12:42

标签: java android timertask

在onCreate上,我运行一个每分钟都重复的任务。我是怎么做到的:

myTimer = new Timer();
    int delay = 30000;   // delay for 30 sec.
    int period = 600000;  // repeat every 60 sec.
    doThis = new TimerTask() {
      public void run() {

                     Log.v("TImer","repeated");
                     wv.reload();

      }
    };

    myTimer.scheduleAtFixedRate(doThis, delay, period);

所有代码都在onCreate中。因此,当应用程序从屏幕上关闭时,我可以在logcat中看到计时器钢块运行,并且除非应用程序被销毁,否则不会停止。因此,在onPause个活动中,我致电myTimer.cancel();,但它没有帮助。即使应用程序不在屏幕上,我仍然可以在logcat中看到更新。那么,如何停止timerTask

3 个答案:

答案 0 :(得分:4)

这是您的代码放入我的文件中,值延迟和周期调整,所以我不必等待这么久。我运行应用程序。我在LogCat中看到了这些消息。我按下Galaxy S3上的主页按钮。然后消息在LogCat中停止。

public class MainActivity extends Activity {
    Timer myTimer;
    TimerTask doThis;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myTimer = new Timer();
        int delay = 0;   // delay for 30 sec.
        int period = 1000;  // repeat every 60 sec.
        doThis = new TimerTask() {
          public void run() {

                         Log.v("TImer","repeated");

          }
        };

        myTimer.scheduleAtFixedRate(doThis, delay, period);
    }

    @Override
    protected void onPause() {
        myTimer.cancel();
        super.onPause();
    }
}

答案 1 :(得分:0)

可能是因为线程已经被发送出去,所以它最后一次运行。在onLoad中将变量设置为true,然后在onPause中将其设置为false。然后在你的计时器任务中,只有在变量为真时运行你的代码。

尽管写入新if语句之外的日志。如果它确实只是最后一次运行它,那么这可能是你的解决方案。但如果在onPause之后仍然多次运行它,那么就不要采取我的解决方案。

答案 2 :(得分:0)

实际答案是onPause方法需要正确定义。

整个故事:
发问者将onPause方法定义错误。这就是问这个问题的原因。

之所以写这篇文章,是因为我花了太多时间阅读问题,答案,代码和注释。真正的答案隐藏在最后一条评论中。