The most correct way to do it would be to check periodically inside doInBackground
if the task was cancelled (i.e. by calling isCancelled
). From http://developer.android.com/reference/android/os/AsyncTask.html:
Cancelling a task :
A task can be cancelled at any time by invoking
cancel(boolean)
. Invoking this method will cause subsequent calls to
isCancelled()
to return true
. After invoking this method,
onCancelled(Object)
, instead of onPostExecute(Object)
will be invoked
after doInBackground(Object[])
returns. To ensure that a task is
cancelled as quickly as possible, you should always check the return
value of isCancelled() periodically from doInBackground(Object[])
, if
possible (inside a loop for instance.)
Check also this blog post if you need more information: http://vikaskanani.wordpress.com/2011/08/03/android-proper-way-to-cancel-asynctask/