title: How to Stop Timer Android
body: <p>following is my code:</p>
  
  <p>In MainActivity.class</p>
  
  <pre><code>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);
  }
  </code></pre>
  
  <p>MyService.class</p>
  
  <pre><code>@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();
  }
  </code></pre>
  
  <p>I am checking the <code>onCheckedChangeListener</code> and calling <code>display_alert</code> function according to the checked radio button.</p>
  
  <p>In <code>display_alert</code> function I was using timer scheduling at fixed rate of 10 seconds and calling <code>myservice</code> class.</p>
  
  <p>So once I checked the <code>radio_on</code> button, it calls my <code>display_aler</code>t function and got the "alert on" in toast. So its working fine.</p>
  
  <p>If I again check <code>radio_off</code> button and then check the <code>radio_on</code> button, I am getting the "alert on" toast, but the toast is coming twice. Similarly if I again select the <code>radio_on</code> button, 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 <code>radio_off</code> button.</p>
  
  <p>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?</p>