I need to download a huge amount of data from the server. It takes at least 10 seconds to download. Here is my code to download using the asyntask class. And I want to cancel the download operation unconditionally if the user presses the home button during the download operation. The problem is ... I am executing the cancel () method, but it does not cancel the load operation. I see that this operation is running in the background in logcat mode, even I quit the application. I just want to stop the execution of doInBackground (). Please help me.
when you click the download button:
dwnldTask = new DownloadTask (); dwnldTask.execute(SERVER_URL);
And here is the 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 a method located in another class called 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); }
source share