Canceling an AsyncTask
Another nice usability touch we can provide for our users is the ability to cancel a task before it completes—for example, if after starting the execution, the user is no longer interested in the operation result. 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 a blocking interruptible function, such as Object.wait()
. When we set the mayInterruptIfRunning
as false
, the AsyncTask won't interrupt the current interruptible blocking operation and the AsyncTask background processing will only finish once the blocking operation terminates.
Note
In well behaved interruptible blocking functions, such as Thread.sleep()
, Thread.join(),
or Object.wait(),
the execution is stopped immediately when the thread...