Question

I have to download huge amount of data from server. It is taking minimum 10 seconds to download. Here is my code to download using asyntask class. And I want to cancel the downloading operation unconditionally if the user clicks on home button while downloading operation is going on. The problem is... I'am executing cancel() method but it is not cancelling the downloading operation. I'am seeing that operation is running in background in logcat view even i came out of application. I just want to stop the execution of doInBackground() method. Please guide/help me.

on click of download button :

  dwnldTask = new DownloadTask ();
  dwnldTask.execute(SERVER_URL);

And here is Asynctask class :

 class DownloadTask extends AsyncTask<String, Void, Object>{
    private Object response = null;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

         displaying progress dialog on UI 
    }
    @Override
    protected Object doInBackground(String... params) {
        try{   

             DataConnection dc = new DataConnection();

             this.response = dc.connectToServer(params[0]);

            if(isCancelled()){
                return null;
            }


        }catch (Exception e) {
            if(isCancelled()){
                return null;
            }   
            e.printStackTrace();
            showToastMSG(e.getMessage());
        }  

        return this.response ;
    }

    @Override
    protected void onPostExecute(Object response) {
        super.onPostExecute(response);

        if(response != null ){ 
            successfully downloaded...  go to next activity
             } 
            cancel progress dialog here
    }

} 

Inside onPause()..

  @Override
protected void onPause() {
    super.onPause();
    if(dwnldTask != null && dwnldTask.getStatus() == AsyncTask.Status.RUNNING){
        dwnldTask.cancel(true);
    }  
     cancel the progress dialog if it is showing

}

Here is the method located in another class named DataConnection...

  public Object connectToServer(String url) throws Exception{
    HttpGet request = new HttpGet(url);
    request.addHeader("accept","application/json");
    HttpResponse response = httpClient.execute(request);   
    HttpEntity httpEntity = response.getEntity();
    InputStream responseInputStream = httpEntity.getContent();
    return myUtilObject.convertInputStreamToString(responseInputStream);
}
Was it helpful?

Solution

I agree with Ran - you didn't write the code of: myUtilObject.convertInputStreamToString but im guessing you loop there over the inputstream with a buffer you predefined its size (maybe with BufferedReader?) - in this loop you should check the stop condition of your async thread - isCancelled() is a good example.

The loop should stop if the thread is canceled, i.e.:

String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is), 1024);
while ((line = rd.readLine()) != null && !isCancelled())
{
     total.append(line);
}

OTHER TIPS

You are checking the isCancelled() method after you perform the download, so there's no reason it would get cancelled in the middle.

Usually you do something like this:

while (!isCancelled()) {
 // Download next buffer..
}

In this case, the loop will stop once a cancel request has been made.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top