Android Canceling AsyncTask


YourAsyncTask task = new YourAsyncTask();

This doesn't stop your task if it was in progress, it just sets the cancelled flag which can be checked by checking the return value of isCancelled() (assuming your code is currently running) by doing this:

class YourAsyncTask extends AsyncTask<Void, Void, Void> {
    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;


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.