title: How can i stop a TimerTask Handler?
body: <p>I am trying to stop a Timer or TimerTask, but the method doesn't destroy the task...</p>
  
  <p>First the code how i set up the timertask:</p>
  
  <pre><code> scanTask = new TimerTask() {
      public void run() {
              handler.post(new Runnable() {
                      public void run() {
                       load_unread();
                       Log.d("TIMER", "Timer set off");
                      }
             });
      }};
  </code></pre>
  
  <p>t=new Timer();
      t.schedule(scanTask, 300, 10000);</p>
  
  <p>and now I'm trying to "kill" this Task at onDestroy:</p>
  
  <pre><code>@Override
  protected void onDestroy() {
      super.onDestroy();
      scanTask.cancel();
      t.cancel();
      t.purge();
      handler.removeCallbacksAndMessages(null);
      System.out.println("Chat destroyed");
  }
  </code></pre>
  
  <p>but this doesn't work? Can you please help me finding a solution?</p>
  
  <p>Thanks! </p>
  
  <p>EDIT: I finally found the answer. Don't know why mine didn't work...</p>
  
  <p>Here the code for everyone who has the same Problem. I think this is a better and more efficient solution anyway:</p>
  
  <p><code> 
      private Handler handler = new Handler();
      runnable.run();</p>
  
  <pre><code>private Runnable runnable = new Runnable() 
  {
  
      public void run() 
      {
           //
           // Do the stuff
           //
  
           handler.postDelayed(this, 1000);
      }
  };
  </code></pre>
  
  <p></code></p>
  
  <p>and to stop:</p>
  
  <p><code></p>
  
  <pre><code>handler.removeCallbacks(runnable);
  </code></pre>
  
  <p></code></p>
  
  <p>taken from here:</p>
  
  <p><a href="https://stackoverflow.com/a/11640073/1956197">https://stackoverflow.com/a/11640073/1956197</a></p>