How does the .cancel(boolean) method of a running AsyncTask work? Here is the documentation:
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 after doInBackground(Object[]) returns. Calling this method guarantees that onPostExecute(Object) is never invoked. After invoking this method, you should check the value returned by isCancelled() periodically from doInBackground(Object[]) to finish the task as early as possible.
The second paragraph implies that it is up to the programmer to return from the doInBackground method as soon as possible after cancel being called (by checking isCancelled() regularly). But in testing, my AsyncTask (doInBackground method) appears to stop straight away even if I don’t do this, after cancel is called. Could anyone explain this? (Logcat doesn’t show anything happening when cancel is called, btw).
protected Void doInBackground(Void... V) {
for (int v=3;v>0;v--){
publishProgress(v);
try {Thread.sleep(1500);} catch (InterruptedException e) {}
}
return null;
}
Also, this happens regardless of the supplied value of mayInrerruptIfRunning, so if it could be explained where this value comes in, that would also be very much appreciated.
There are a few core methods (“blocking methods”), such as
Thread.sleep(), which themselves check for thread interruption and throw the exception.