I am dealing with quite a bit of legacy AsyncTask code and have to write some myself too in our codebase. But, the careful reading of the cancel()
method from the docs has confused me quite a bit. The docs say:
Attempts to cancel execution of this task. This attempt will fail if the task has already completed, already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the
mayInterruptIfRunning
parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.Calling this method will result in
onCancelled(Object)
being invoked on the UI thread afterdoInBackground(Object[])
returns. Calling this method guarantees thatonPostExecute(Object)
is never invoked. After invoking this method, you should check the value returned byisCancelled()
periodically fromdoInBackground(Object[])
to finish the task as early as possible.
So, there might be a scenario where the AsyncTask has finished and returned from doInBackground()
but before calling onPostExecute()
, the task was canceled through cancel()
which resulted in a call to onPostExecute()
anyway. This might be dangerous if the cancellation was initiated from onPause()
of Activity
.
Also, this question on SO supports the documented behavior of cancellation: onPostExecute on cancelled AsyncTask
So, should I start checking for if(isCanceled())
at the start of onPostExecute()
from now on?