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