In my application I download and parse a html page. However, I want to be able to stop the download in its tracks (i.e. when the user hits cancel).
This is the code I use now, which is being called from doInBackground from ASyncTask.
How do I cancel this request from outside of the ASyncTask?
I currently use 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;
}
Ok, I believe I've solved this.
In my Activity class I have a variable (boolean)
failed. Also, I have a privateDownloaderclass within the activity which extendsASyncTask. This way, theDownloaderclass has access to thefailedboolean. When the Activity launches, it starts theDownloadertask and a progress dialog pops up. When the task finishes, it closes the dialog and then goes on processing the downloaded content.However, when the user cancels the progress dialog,
failedis set to true, and the user is sent back to the previous activity by a call tofinished. In the meantime,Downloaderis still busy downloading. Because the results are now unneccessary, we want it to stop using resources asap. In order to accomplish this, I have broken up thedoInBackgroundmethod in as much steps as possible. After each step I check iffailedis stillfalse, when it is set totrue, it simply doesn't go to the next step. See it in action below. Furthemore, theBufferedReader readeris public, and in theonCancelledmethod I executereader.close(). This will throw all sorts of exceptions, but these are properly caught.I know that I could have broken up the downloading process in even tinier bits, but I am downloading very small files, so it's not that important.