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/
source share