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?
Just discovered that AlertDialogs
's boolean cancel(...);
I've been using everywhere actually does nothing. Great.
So...
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.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
// actually could set running = false; right here, but I'll
// stick to contract.
cancel(true);
}
});
}
@Override
protected void onPreExecute() {
progressDialog.show();
}
@Override
protected void onCancelled() {
running = false;
}
@Override
protected Void doInBackground(Void... params) {
while (running) {
// does the hard work
}
return null;
}
// ...
}
If you're doing computations:
isCancelled()
periodically.If you're doing a HTTP request:
HttpGet
or HttpPost
somewhere (eg. a public field).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
.