I have an AsyncTask in which I show a ProgressDialog in the onPreExecute, and hide it again in onPostExecute, something like
final class UploadTask extends AsyncTask {
ProgressDialog dialog = new ProgressDialog(...);
protected onPreExecute() {
dialog.show();
}
protected onPostExecute() {
dialog.hide();
}
};
The dialog is cancellable and indeed goes away when I press the cancel button during execution of the AsyncTask.
When this happens, I would like to run some code to cancel the AsyncTask as well (right now, even thought he ProgressDialog goes away, the AsyncTask keeps running and eventually completes). I tried deriving my own class from ProgressDialog and then do
setOnDismissListener(new OnDismissListener() {
@Override public void onDismiss(DialogInterface d) {
/* do something */
}
};
(or something similar with an OnCancelListener), but this simply never gets called.
Any ideas? I just need some mechanism for the user to cancel a running AsyncTask while a ProgressDialog is showing.
AsyncTask must be subclassed to be used. The subclass will override at least one method ( doInBackground(Params...) ), and most often will override a second one ( onPostExecute(Result) .)
Cancelling a task A task can be cancelled at any time by invoking cancel(boolean) . Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(java.
Why Android AsyncTask is Deprecated? Here is the official reason it is deprecated. AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes.
Generally you should set a flag in your AsyncTask class or return an appropriate result from your doInBackground() so that, in your onPostExecute() , you can check if you could finish what you want or if your work was cancelled in the middle. Save this answer.
I haven't tested this, but try something like this:
final class UploadTask extends AsyncTask implements OnDismissListener{
ProgressDialog dialog = new ProgressDialog(...);
protected onPreExecute() {
dialog.setOnDismissListener(this);
dialog.show();
}
protected onPostExecute() {
dialog.hide();
}
@Override
public void onDismiss(DialogInterface dialog) {
this.cancel(true);
}
};
I think you are looking for this: onCancelled()
http://developer.android.com/reference/android/os/AsyncTask.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With