我有一個AsyncTask加載一些內容並將其放在屏幕上。下面的代碼:Android中的AsyncTask不會退出
private class ContentLoader extends AsyncTask<Void, Void, Void>{
private boolean running = false;
protected Void doInBackground(Void... params){
running = true;
while (running){
try {
publishProgress();
Thread.sleep(3000);
} catch (InterruptedException e) {
Log.d("ContentLoader", String.valueOf(e));
}
}
return null;
}
protected void onProgressUpdate(Void... progressParams){
setContents();
}
public void exit(){
Log.d("ContentLoader-exit before", String.valueOf(running));
running = false;
Log.d("ContentLoader-exit after", String.valueOf(running));
}
}
的setContents() - 方法加載從一個SQLite數據庫的一些文字,並將其設置爲TextViews,直到我嘗試退出任務,一切工作正常。當我調用退出方法時,兩個日誌條目都顯示值「false」並且循環繼續。
我把從我的活動的OnCreate法的任務是:我希望它在onBackPressed退出
public class MainActivity extends ActionBarActivity {
ContentLoader contentLoader = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contentLoader = new ContentLoader();
contentLoader.execute();
}
:
@Override
public void onBackPressed(){
super.onBackPressed();
if (contentLoader != null){
contentLoader.exit();
}
finish();
那麼,怎樣才能讓這件事退出嗎?謝謝你的回答!
你在哪裏設置running = false?在doInBackground裏面? – iGoDa
在日誌之間的exit-method內。 –
sry,我的意思是,你沒有調用while(running)中的exit方法,因此async任務不會退出 – iGoDa