Canceling AsyncTask
Another nice usability touch we can provide for our users is the ability to cancel a task before it completes—for example, if the task depends on some user input and, after starting the execution, the user realizes that they have provided the wrong value. AsyncTask
provides support for cancellation with the cancel
method.
public final boolean cancel(boolean mayInterruptIfRunning)
The mayInterruptIfRunning
parameter allows us to specify whether an AsyncTask
thread that is in an interruptible state may actually be interrupted—for example, if our doInBackground
code is performing interruptible I/O.
Simply invoking cancel
is not sufficient to cause our task to finish early. We need to actively support cancellation by periodically checking the value returned from isCancelled
and reacting appropriately in doInBackground
.
First, let's set up our ProgressDialog
to trigger the AsyncTask's cancel
method by adding a few lines to onPreExecute
:
progress.setCancelable(true); progress.setOnCancelListener...