如何在android中停止计时器?

问题描述:

我正在开发一个应用程序,它在特定的时间段内将消息发送到特定的号码。 问题在于,在那段时间之后它会继续发送该消息。如何在特定时间后停止计时器以停止发送该消息?如何在android中停止计时器?

+2

我会帮助,如果你想展示你的一些代码,采用定时器。 – 2011-02-14 15:17:45

+0

不明白这是一个脱离主题的问题!它有15票,8星也接受答案有45 ups! – 2017-03-02 04:37:53

 CountDownTimer waitTimer; 
    waitTimer = new CountDownTimer(60000, 300) { 

     public void onTick(long millisUntilFinished) { 
      //called every 300 milliseconds, which could be used to 
      //send messages or some other action 
     } 

     public void onFinish() { 
      //After 60000 milliseconds (60 sec) finish current 
      //if you would like to execute something when time finishes   
     } 
    }.start(); 

提前停止计时器:

 if(waitTimer != null) { 
     waitTimer.cancel(); 
     waitTimer = null; 
    } 

在java.util.timer中,可以使用.cancel()来停止计时器并清除所有挂起的任务。

+4

但实际上这是不正确的,我叫.cancel()和计时器并没有停止! – bebosh 2015-02-02 15:19:10

+0

@bebosh它在`countDownTimer.called();`被调用时起作用。 – 030 2015-04-06 23:49:41

它说timer()在android上不可用?您可能会发现这篇文章很有用。

http://developer.android.com/resources/articles/timed-ui-updates.html


我错了。定时器()可用。看来你要么实现它的方式是一次性操作:

schedule(TimerTask task, Date when) // Schedule a task for single execution. 

或者你在第一次执行后取消:

cancel() // Cancels the Timer and all scheduled tasks. 

http://developer.android.com/reference/java/util/Timer.html

+0

第一个链接返回错误404 – guisantogui 2015-05-06 01:46:06

+1

它可能已被删除。在这里阅读:http://developers.androidcn.com/resources/articles/timed-ui-updates.html – dongshengcn 2015-05-06 15:59:05

和..我们必须为GC调用“waitTimer.purge()”。如果你不再使用Timer,“清除()”! “purge()”从任务队列中删除所有取消的任务。

if(waitTimer != null) { 
    waitTimer.cancel(); 
    waitTimer.purge(); 
    waitTimer = null; 
} 

我有一个类似的问题,它是由定位初始化的位置引起的。

它被放置在一个被调用的方法中。

试试这个:

Timer waitTimer; 

    void exampleMethod() { 

    if (waitTimer == null) { 
    //initialize your Timer here 
    ... 
    } 

“取消()” 方法只取消了最新的定时器。年长者被忽视,并没有停止跑步。

我们可以安排定时器来完成这项工作。时间结束后我们设置的消息不会发送。

这是代码。

Timer timer=new Timer(); 
timer.scheduleAtFixedRate(new TimerTask() { 
    @Override 
    public void run() { 
      //here you can write the code for send the message 
     } 
    }, 10, 60000); 

在这里,我们在调用方法,

公共无效scheduleAtFixedRate(TimerTask的任务,长时间的延迟,周期长)

在这里,

任务:计划任务

延迟:第一次执行之前的时间量(以毫秒为单位)。

期间:后续执行之间的时间量(以毫秒为单位)。

欲了解更多信息,可以参考: Android Developer

可以通过调用停止计时,

timer.cancel(); 

我有一个类似的问题:每次我按下一个特定的按钮,我创建了一个新的计时器。

my_timer = new Timer("MY_TIMER"); 
my_timer.schedule(new TimerTask() { 
... 
} 

从活动退出我删除定时器:

if(my_timer!=null){ 
my_timer.cancel(); 
my_timer = null; 
} 

但它是不够的,因为cancel()方法只取消了最新的定时器。年长者被忽视,并没有停止跑步。 purge()方法对我无用。 我刚刚解决了检查Timer实例化的问题:

if(my_timer == null){ 
my_timer = new Timer("MY_TIMER"); 
my_timer.schedule(new TimerTask() { 
... 
} 
}