In every AsyncTask, you implement the
onCancelled
method:
@Override
protected void onCancelled() {
}
Now, calling
cancel()
on an AsyncTask will cause
onCancelled()
instead of
onPostExecute()
to be executed when
doInBackground()
is finished. Notice that
onCancel
isn't immediately called (as said, it's called when
doInBackground
is finished), but a flag is set, which can be accessed via
yourAsyncTask.isCancelled()
. This is why it's proper practice (and recommended by Android development guidelines) to periodically check this flag from your
doInBackground
method, usually in a loop:
@Override
protected Object doInBackground(Object... x) {
while (!isCancelled()) {
return workProcessingResult;
}
return null;
}
Further reading
here[^]