这是我的固定速率计时器代码。当 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/