如何停止计时器 Android

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10311087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:14:15  来源:igfitidea点击:

How to Stop Timer Android

androidservicetimerandroid-contexttimertask

提问by Dray

following is my code:

以下是我的代码:

In MainActivity.class

在 MainActivity.class 中

private OnCheckedChangeListener alert_on_off_listener = new OnCheckedChangeListener(){
    public void onCheckedChanged(RadioGroup groupname, int CheckedButtonId) {

         if(CheckedButtonId==R.id.radiobutton_on){
             Toast.makeText(getApplicationContext(), "radio on", Toast.LENGTH_LONG).show();
             alert_on = true;
             display_alert();    
         }
         else{
             alert_on = false;
         }   
    }
};

public void display_alert(){

    int delay = 10000;  
    Timer timer =new Timer();
    timer.scheduleAtFixedRate(new TimerTask()
    {
        public void run() 
            {
                Intent myIntent = new Intent(HoraWatchActivity.this,MyService.class);
                startService(myIntent);
            }
    }, delay,10000);
}

MyService.class

我的服务类

@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    if(MainActivity.alert_on)
       Toast.makeText(getApplicationContext(), "Alert is On", Toast.LENGTH_LONG).show();
    else
       Toast.makeText(getApplicationContext(), "Alert is Off",Toast.LENGTH_LONG).show();
}

I am checking the onCheckedChangeListenerand calling display_alertfunction according to the checked radio button.

我正在根据选中的单选按钮检查onCheckedChangeListener和调用display_alert功能。

In display_alertfunction I was using timer scheduling at fixed rate of 10 seconds and calling myserviceclass.

display_alert函数中,我以 10 秒的固定速率使用计时器调度并调用myservice类。

So once I checked the radio_onbutton, it calls my display_alert function and got the "alert on" in toast. So its working fine.

所以一旦我检查了radio_on按钮,它就会调用我的display_alert 函数并在吐司中获得“警报”。所以它的工作正常。

If I again check radio_offbutton and then check the radio_onbutton, I am getting the "alert on" toast, but the toast is coming twice. Similarly if I again select the radio_onbutton, the toast is displaying for the third time, but I need only once. This was due to that the timer is running for every 10 seconds. I want to stop the timer once I click the radio_offbutton.

如果我再次检查radio_off按钮然后检查radio_on按钮,我会收到“警报”吐司,但吐司要来两次。同样,如果我再次选择radio_on按钮,吐司将第三次显示,但我只需要一次。这是因为计时器每 10 秒运行一次。单击radio_off按钮后,我想停止计时器。

The problem is, once I started the timer, I was not stopping it further. When and how shall I cancel the timer tasks in my class?

问题是,一旦我启动了计时器,我并没有进一步停止它。我何时以及如何取消班级中的计时任务?

回答by Eduardo

First, create your TimerTask on a separate way:

首先,以单独的方式创建您的 TimerTask:

class MyTimerTask extends TimerTask {
  public void run() {
    Intent myIntent = new Intent(HoraWatchActivity.this,MyService.class);
    startService(myIntent);
  }
}

Declare it somewhere, of course visible to your OnCheckedChangeListener:

在某处声明它,当然对您的 OnCheckedChangeListener 可见:

MyTimerTask myTimerTask;

Schedule it:

安排它:

public void display_alert() {
  int delay = 10000;  
  myTimerTask = new MyTimerTask();
  Timer timer = new Timer();
  timer.scheduleAtFixedRate(myTimerTask, delay, 10000);
}

And then modify your code to:

然后将您的代码修改为:

private OnCheckedChangeListener alert_on_off_listener = new OnCheckedChangeListener(){
public void onCheckedChanged(RadioGroup groupname, int CheckedButtonId) {

     if(CheckedButtonId==R.id.radiobutton_on){
         Toast.makeText(getApplicationContext(), "radio on", Toast.LENGTH_LONG).show();
         alert_on = true;
         display_alert();    
     }
     else{
         myTimerTask.cancel();
         alert_on = false;
     }   
}
};

回答by Shankar Agarwal

if(timerTask!=null){
    timer.cancel();
}

you can use the code to stop/cancel timer

您可以使用代码来停止/取消计时器

回答by Mohammed Azharuddin Shaikh

First create a class extends TimerTask, make object of it and handle the operation on that object.

首先创建一个类扩展 TimerTask,创建它的对象并处理该对象上的操作。

int delay = 10000;  
Timer timer =new Timer();
myTimer mTask= new myTimer();
timer.scheduleAtFixedRate(mTask, delay, 10000);

public class myTimer extends TimerTask
{
    @Override
    public void run() {
        Intent myIntent = new Intent(HoraWatchActivity.this,MyService.class);
            startService(myIntent);         
    }
}

when your mTask works get over just

当你的 mTask 工作结束时

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

thats it.

就是这样。

回答by Vaibhav Agrawal

I am able to stop a timer and a task using following code:

我可以使用以下代码停止计时器和任务:

    if(null != timer)
    {

        timer.cancel();
        Log.i(LOG_TAG,"Number of cancelled tasks purged: " + timer.purge());
        timer = null;
    }

    if(task != null)
    {
        Log.i(LOG_TAG,"Tracking cancellation status: " + task.cancel());
        task = null;
    }