我的應用程序似乎有問題。發生什麼事是我想在用戶關閉程序時殺掉我的異步任務。我背後的推理是,我有一個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);
}
感謝所有貢獻者!
#####解決方案################解決方案
一個例子用於取消的AsyncTask HTTP停止此服務:// WWW .quicktips.in/correct-way-to-cancel-an-asynctask-in-android/ –
感謝您使用您的解決方案更新您的文章。我想知道,只需在OnStop方法中添加此Task.cancel(true)就足夠了,還是您還需要在doInBackground中監視isCancelled()方法?只是問,因爲開發人員文檔中的一些其他人在你的帖子中提到必須同時執行這兩個操作,但你只能在解決方案中提到。謝謝! – gabe3vino