2015-07-03 60 views
0

我有一個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(); 

那麼,怎樣才能讓這件事退出嗎?謝謝你的回答!

+1

你在哪裏設置running = false?在doInBackground裏面? – iGoDa

+0

在日誌之間的exit-method內。 –

+0

sry,我的意思是,你沒有調用while(running)中的exit方法,因此async任務不會退出 – iGoDa

回答

0

嘗試使用cancel方法取消AsyncTask並在while循環條件中使用isCancelled方法。

下面是一個例子:

private class ContentLoader extends AsyncTask<Void, Void, Void>{ 

    protected Void doInBackground(Void... params){ 
     running = true; 
     while (!isCancelled()){ 
      try { 
       publishProgress(); 
       Thread.sleep(3000); 
      } catch (InterruptedException e) { 
       Log.d("ContentLoader", String.valueOf(e)); 
      } 
     } 
     return null; 
    } 

    protected void onProgressUpdate(Void... progressParams){ 
     setContents(); 
    } 

} 

然後用cancel方法來取消任務

ContentLoader contentLoader = new ContentLoader(); 
contentLoader.execute(); 
contentLoader.cancel(true); 
0

使用contentLoader.cancel(boolean mayInteruptIfRunning)其中布爾mayInteruptIfRunning如果屬實將interupt正在運行的線程否則將允許它完成,然後取消它。

而且你可以檢查使用contentLoader.isCancelled()

0

您需要使用cancel馬託狀態:

@Override 
public void onBackPressed(){ 
    super.onBackPressed(); 
    if (contentLoader != null){ 
     contentLoader.cancel(); 
    } 
    finish(); 

如果您的AsyncTask有一個循環做:

@Override 
Void doInBackground(Void... params) { 
    for(;;) 
     if(isCancelled()) 
      return null; 
} 

如果你使用類似URLConnection的東西,請這樣做

@Override 
Void doInBackground(Void... params) { 
    URLConnetcion uc = new URLConnection(new URL()); 

    if(isCancelled()) 
     return null; 
    else 
     //your normal processing 
     process(); 
}