重新安排计时器的android [英] Reschedule timer in android

查看:205
本文介绍了重新安排计时器的android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能重新安排一个计时器。我曾试图取消计时器/ TimerTask的和,并安排它采用的方法了。但它显示出异常错误:

异常errorjava.lang.IllegalStateException:TimerTask的已定

code我已经用它:

私人定时器定时=新的定时器(alertTimer,真正的);
公共无效reScheduleTimer(INT持续时间){
    timer.cancel();
    timer.schedule(TimerTask的,1000L,持续时间* 1000L);
}

解决方案

如果你看到Timer.cancel(文档),你会看到这样的:

取消定时器和所有预定的任务。如果有一个当前正在运行的任务,它不会受到影响。没有更多的任务可能安排在这个计时器。后续调用什么也不做。

您需要初始化,当你重新安排一个新的计时器:

编辑:

 公共无效reScheduleTimer(INT持续时间){
  定时器=新的定时器(alertTimer,真正的);
  TimerTask的=新MyTimerTask();
  timer.schedule(TimerTask的,1000L,持续时间* 1000L);
}

私有类MyTimerTask扩展的TimerTask {
  @覆盖
  公共无效的run(){
    //做的东西
  }
}
 

How can I reschedule a timer. I have tried to cancel the timer/timertask and and schedule it again using a method. But its showing an exception error:

Exception errorjava.lang.IllegalStateException: TimerTask is scheduled already

Code I have used it :

private Timer timer = new Timer("alertTimer",true);
public void reScheduleTimer(int duration) {
    timer.cancel();
    timer.schedule(timerTask, 1000L, duration * 1000L);
}

解决方案

If you see the documentation on Timer.cancel() you'll see this:

"Cancels the Timer and all scheduled tasks. If there is a currently running task it is not affected. No more tasks may be scheduled on this Timer. Subsequent calls do nothing."

You'll need to initialize a new Timer when you are rescheduling:

EDIT:

public void reScheduleTimer(int duration) {
  timer = new Timer("alertTimer",true);
  timerTask = new MyTimerTask();
  timer.schedule(timerTask, 1000L, duration * 1000L);
}

private class MyTimerTask extends TimerTask {
  @Override
  public void run() {
    // Do stuff
  }
}

这篇关于重新安排计时器的android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆