Canceling AsyncTask
suggest changeYourAsyncTask 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents