java - 要在应用程序进入后台时暂停 scheduleAtFixedRate 计时器?

标签 java android timer

这是我的固定速率计时器代码。当 Activity 进入 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);

最佳答案

您可以使用 Timer.cancel()

  • 终止此计时器,丢弃所有当前计划的任务。不干扰当前正在执行的任务(如果存在)。计时器终止后,其执行线程将正常终止,并且不再有任何任务可以安排在其上。

将定时器声明为全局的

t = new Timer();

试试这个

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

timer should start work as app comes to onResume();:

您需要在onResume() 中启动Timer 试试这个

@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);
    }

关于java - 要在应用程序进入后台时暂停 scheduleAtFixedRate 计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51379761/

相关文章:

python - 用空格键中断计时器

ios - dispatch_source_t 处理函数的计时问题——我是否遵循正确的调度计时器模式?

java - Java 中的本地化日期格式

android - 在 Android 模拟器上启动 phonegap 应用程序时出现“连接到服务器失败”错误

android - 如何在我的 Android 应用程序中播放 YouTube 视频?

android - Admob - 横幅显示黑色背景且无广告

python - 6 分钟后重新启动脚本

Java UncaughtExceptionHandler + LOG4J + Maven

java - 关于旋转text3d

java - Swing 中的根 Pane 是什么?