在android中重新安排计时器

编程入门 行业动态 更新时间:2024-10-28 11:25:06
本文介绍了在android中重新安排计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何重新安排计时器.我试图取消计时器/计时器任务并使用一种方法重新安排它.但它显示异常错误:

<前>异常错误java.lang.IllegalStateException: TimerTask 已经安排好了

我用过的代码:

<前>private Timer timer = new Timer("alertTimer",true);公共无效reScheduleTimer(int持续时间){定时器.取消();timer.schedule(timerTask, 1000L, duration * 1000L);}

解决方案

如果您查看有关 Timer.cancel() 的文档,您将看到:

取消计时器和所有计划任务.如果有当前正在运行的任务,它不会受到影响.不能在此计时器上安排更多任务.后续调用不执行任何操作."

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

public void reScheduleTimer(int duration) {timer = new Timer("alertTimer",true);timerTask = new MyTimerTask();timer.schedule(timerTask, 1000L, duration * 1000L);}私有类 MyTimerTask 扩展了 TimerTask {@覆盖公共无效运行(){//做东西}}

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屋!

更多推荐

[db:关键词]

本文发布于:2023-03-28 18:33:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/736938.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:计时器   android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!