Canceling AsyncTask

suggest change
YourAsyncTask task = new YourAsyncTask();
task.execute();
task.cancel(true);

cancel(true) asks the task to interrupt. It does not abort doInBackground by itself. It sets the cancelled flag. Check isCancelled() while the work is running:

public class YourAsyncTask extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        while(!isCancelled()) {
            ... doing long task stuff
            //Do something, you need, upload part of file, for example
            if (isCancelled()) {    
                return null; // Task was detected as canceled
            }
            if (yourTaskCompleted) {
                return null;
            }
        }
        return null;
    }
}

Note

If an AsyncTask is canceled while doInBackground(Params... params) is still executing then the method onPostExecute(Result result) will NOT be called after doInBackground(Params... params) returns. The AsyncTask will instead call the onCancelled(Result result) to indicate that the task was cancelled during execution.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents