AsyncTask is not cancelling the long running operation in android

匿名 (未验证) 提交于 2019-12-03 08:54:24

问题:

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); }

回答1:

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); }


回答2:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!