Ideal way to cancel an executing AsyncTask


I am running remote audio-file-fetching and audio file playback operations in a background thread using AsyncTask. A Cancellable progress bar is shown for the time the fetch operation runs.

I want to cancel/abort the AsyncTask run when the user cancels (decides against) the operation. What is the ideal way to handle such a case?

4/29/2010 6:32:30 AM

Accepted Answer

Just discovered that AlertDialogs's boolean cancel(...); I've been using everywhere actually does nothing. Great.

public class MyTask extends AsyncTask<Void, Void, Void> {

    private volatile boolean running = true;
    private final ProgressDialog progressDialog;

    public MyTask(Context ctx) {
        progressDialog = gimmeOne(ctx);

        progressDialog.setOnCancelListener(new OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
                // actually could set running = false; right here, but I'll
                // stick to contract.


    protected void onPreExecute() {;

    protected void onCancelled() {
        running = false;

    protected Void doInBackground(Void... params) {

        while (running) {
            // does the hard work
        return null;

    // ...

4/29/2010 7:28:29 PM

If you're doing computations:

  • You have to check isCancelled() periodically.

If you're doing a HTTP request:

  • Save the instance of your HttpGet or HttpPost somewhere (eg. a public field).
  • After calling cancel, call request.abort(). This will cause IOException be thrown inside your doInBackground.

In my case, I had a connector class which I used in various AsyncTasks. To keep it simple, I added a new abortAllRequests method to that class and called this method directly after calling cancel.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow