首页 > 解决方案 > 在应用程序进入后台时暂停 scheduleAtFixedRate Timer?

问题描述

这是我的固定速率计时器代码。我可以在活动进行时暂停此计时器吗onPause();?如果是这样,那么您建议我在onPause();方法和计时器中添加什么,应该在应用程序出现时开始工作onResume();

    //Declare the timer
    t = new Timer();

    //Set the schedule function and rate
    t.scheduleAtFixedRate(new TimerTask() {
                              @Override
                              public void run() {
                                  // code here
                              }
                          },
            //Set how long before to start calling the TimerTask (in milliseconds)
            20000,
            //Set the amount of time between each execution (in milliseconds)
            40000);

标签: javaandroidtimer

解决方案


您可以使用Timer.cancel()

  • 终止此计时器,丢弃任何当前计划的任务。不干扰当前正在执行的任务(如果存在)。一旦计时器被终止,它的执行线程就会优雅地终止,并且不能在其上安排更多任务。

将定时器声明为全局

t = new Timer();

试试这个

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

当应用程序到达 onResume(); 时,计时器应该开始工作:

你需要从Timer试试 onResume() 这个

@Override
    protected void onResume() {
        super.onResume();

        t.scheduleAtFixedRate(new TimerTask() {
                                  @Override
                                  public void run() {
                                      // code here
                                  }
                              },
                //Set how long before to start calling the TimerTask (in milliseconds)
                20000,
                //Set the amount of time between each execution (in milliseconds)
                40000);
    }

推荐阅读