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 ...

Get Asynchronous Android now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.