title: Cancel AsyncTask on app exit SOVLED
body: <p>I seem to have a problem with my application. What's going on is I want to kill my Asynchronous Task when the user closes the program. My reasoning behind this is that I have a StopWatch that runs off an AsyncTask,  and when the user closes the program, the Task continues to run and takes up memory. I would like to cancel the task using this method:</p>
  
  <pre><code> Task.cancel(true);
  </code></pre>
  
  <p>But I don't know when to make the call in my activity. How would I do so? Here is the task I am running:</p>
  
  <pre><code> public class timer extends AsyncTask&lt;String, String, String&gt; {
  
      @Override               
  protected String doInBackground(String... params) {
      while(true){    
      while(milli &lt; 1000 &amp;&amp; running){ //running and other vars are arbitrary variables
              running = true;
              milli++;
              try{                
                  Thread.sleep(1);                
              }
              catch(Exception e1){
                  System.out.println(e1);
              }
              if(milli == 1000){
                  milli = 0;
                  secs++;         
              }
              if(secs == 60){
                  secs = 0;
                  mins++;             
              }
              if(mins == 60){
                  hours++;
                  mins = 0;
              }                       
              this.publishProgress(milli+":"+secs+":"+mins+":"+hours);            }               
          }
      return null;
      }   
      protected void onProgressUpdate(String... values) {
          super.onProgressUpdate(values);
          TextView display = (TextView) findViewById(R.id.textView1);
                   display.setText(values[0]);
      }
      }
  </code></pre>
  
  #####SOLUTION################SOLUTION
  
  <p>I kind of took a bit from everyone, but I ultimately figured it out myself. I overwrote the onStop method of activity like so:</p>
  
  <pre><code>protected void onStop(){
  super.onStop();
  Task.cancel(true);
  }
  </code></pre>
  
  <p>Thanks to all the contributors!</p>
  
  #####SOLUTION################SOLUTION