2014-02-25 23 views
1

我的應用程序似乎有問題。發生什麼事是我想在用戶關閉程序時殺掉我的異步任務。我背後的推理是,我有一個StopWatch運行一個AsyncTask,當用戶關閉程序時,任務繼續運行並佔用內存。我想取消使用此方法的任務:在應用程序退出時取消AsyncTask SOVLED

Task.cancel(true); 

但我不知道何時在我的活動中撥打電話。我會怎麼做?這裏是我正在運行的任務:

public class timer extends AsyncTask<String, String, String> { 

    @Override    
protected String doInBackground(String... params) { 
    while(true){  
    while(milli < 1000 && 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]); 
    } 
    } 
##### SOLUTION ################ SOLUTION

我種了從大家一點,但我最終自己想出了它。我重寫了onStop方法的活動,如下所示:

protected void onStop(){ 
super.onStop(); 
Task.cancel(true); 
} 

感謝所有貢獻者!

#####解決方案################解決方案
+0

一個例子用於取消的AsyncTask HTTP停止此服務:// WWW .quicktips.in/correct-way-to-cancel-an-asynctask-in-android/ –

+0

感謝您使用您的解決方案更新您的文章。我想知道,只需在OnStop方法中添加此Task.cancel(true)就足夠了,還是您還需要在doInBackground中監視isCancelled()方法?只是問,因爲開發人員文檔中的一些其他人在你的帖子中提到必須同時執行這兩個操作,但你只能在解決方案中提到。謝謝! – gabe3vino

回答

2

如果你想阻止你可以使用asyncTask.cancel(true/false);true異步任務指定的android系統停止該服務,甚至就已經開始, false指定了Android系統,如果它已經開始不停止這項任務。 如果要在活動失去其交互寫在onPause() 或者如果你想在活動時間取消摧毀叫它onDestroy() for more detail check this

2

看看Activity的生命週期。在this link上有一個很好的圖表。

您想在onStart()/ onResume()中啓動計時器,並在onStop()/ onPause()中停止它。

請注意,您需要選擇一個一致的onStart/onStop或onResume/onPause對以獲得一致的行爲。