2011-02-06 99 views
0

在我的應用程序中,我下載並解析了一個html頁面。不過,我希望能夠在其曲目中停止下載(即當用戶點擊取消時)。Android停止下載

這是我現在使用的代碼,它正在從doInBackground稱爲從的AsyncTask。

如何取消從的AsyncTask外的這一要求?

我目前使用htmlcleaner

HtmlCleaner cleaner = new HtmlCleaner(); 
    CleanerProperties props = cleaner.getProperties(); 
    props.setAllowHtmlInsideAttributes(true); 
    props.setAllowMultiWordAttributes(true); 
    props.setRecognizeUnicodeChars(true); 
    props.setOmitComments(true); 
    try { 
     URL url = new URL(urlstring); 
     URLConnection conn = url.openConnection(); 
     TagNode node = cleaner.clean(new InputStreamReader(conn.getInputStream())); 
     return node; 
    } catch (Exception e) { 
     failed = true; 
     return; 
    } 

回答

1

好吧,我相信我已經解決了這個。

在我的活動我班有一個變量(布爾)failed。此外,我在ASyncTask的活動範圍內有私人Downloader班。這樣,Downloader類可以訪問failed布爾值。當活動啓動時,它會啓動Downloader任務並彈出一個進度對話框。任務完成後,會關閉對話框,然後繼續處理下載的內容。

但是,當用戶取消進度對話框時,failed設置爲true,並且通過調用finished將用戶發送回先前的活動。與此同時,Downloader仍在忙於下載。由於結果現在不需要,我們希望它儘快停止使用資源。爲了做到這一點,我已儘可能多地分解了doInBackground方法。每個步驟後我檢查failed仍然false,當它被設置爲true,它根本不進入下一個步驟。請參閱下面的操作。另外,BufferedReader reader是公開的,並且在onCancelled方法中我執行reader.close()。這會拋出各種例外情況,但這些例外都被正確地捕捉到了。

public void DoInBackground(.........) { 
    try { 
     URL url = new URL(uri); 
     URLConnection conn = url.openConnection(); 
     if (!failed) { 
      isr = new InputStreamReader(conn.getInputStream()); 
      if (!failed) { 
       reader = new BufferedReader(isr); 
       publishProgress(1); 
       if (!failed) { 
        TagNode node = cleaner.clean(reader); 
        publishProgress(2); 
        return node; 
       } 
      } 
     } 
    } catch (Exception e) { 
      failed = true; 
      Log.v("error",""+e); 
    } 
} 

@Override 
protected void onCancelled() { 
    failed = true; 
    if (reader != null) 
     try { 
      reader.close(); 
     } catch (IOException e) { 
      failed = true; 
     } 
    if (isr != null) 
     try { 
      isr.close(); 
     } catch (IOException e) { 
     } 
} 

我知道我可以打碎更小的下載過程,但是我下載的文件非常小,所以並不重要。

1

你不能使用AsyncTask.cancel()?你應該能夠再使用onCancelled回調返回的主要活動..

+0

這是否也會自動停止下載?我使用URLConnection類下載。 – 2011-02-06 16:49:43