How to Stop Timer Android

亡梦爱人 提交于 2019-12-08 20:46:30

First, create your TimerTask on a separate way:

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:

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;
     }   
}
};
if(timerTask!=null){
    timer.cancel();
}

you can use the code to stop/cancel timer

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

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

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

thats it.

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;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!