When I develop an Android application, how can I cancel running AsyncTask?

Possible duplicate:
Ideal way to cancel AsyncTask execution

When I developed the Android application, I used AsyncTask to download something, I used progressDialog to show the progress of this AsyncTask, now When I click the back button, I want to cancel this AsycTask , I called AsycTask.cancel() , but he does not work. How can I cancel running AsyncTask?

+4
source share
3 answers

The most correct way to do this is to periodically check inside doInBackground if the task has been canceled (i.e. by calling isCancelled ). From http://developer.android.com/reference/android/os/AsyncTask.html :

Cancel a task:

A task can be canceled at any time by calling cancel(boolean) . Calling this method will result in subsequent calls to isCancelled() to return true . After calling this method, onCancelled(Object) , instead of onPostExecute(Object) will be called after doInBackground(Object[]) returns. To ensure that the task is canceled as quickly as possible, you should always check the return value of isCancelled () periodically from doInBackground(Object[]) , if possible (inside a loop, for example.)

Also check out this blog post if you need more information: http://vikaskanani.wordpress.com/2011/08/03/android-proper-way-to-cancel-asynctask/

0
source
  class ImplementAsynctask extends AsyncTask implements OnDismissListener{ ProgressDialog dialog = new ProgressDialog(ActivityName.this); protected onPreExecute() { //do something and show progress dialog } protected onPostExecute() { //cancel dialog after completion } @Override public void onDismiss(DialogInterface dialog) { //cancel AsycTask in between. this.cancel(true); } }; 
+1
source

follow these steps when you click the back button:

declare your Aynctask global variable as follows:

 //AysncTask class private contactListAsync async; if(async != null){ async.cancel(true); async= null; } 
0
source

All Articles