In my android app I use AsynTask with Progress Dialog (Please wait login in ...) for logining user with my web page (web service function inside AsynTask)
I want to dismiss Progress Dialog and cancel AsynTask when user click on Back button on device.
I can't find that kind of example, for interrupting AsynTask. I read abouth cancel(boolean) but I don't know how to call from UI.
Can anyone give me idea.
Thanks
ProgressDialog progressDialog = ProgressDialog.show(ActivityName.this,
"Title",
"Message");
progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
// Do something...
}
});
The setCancelable(true) method sets whether the dialog is cancelable with the BACK key. You can execute finishing codes through setOnCancelListener -> onCancel method.
public MyActivity extends Activity {
private MyAsyncTask task;
public onCreate() {
task = new MyAsyncTask(); // MyAsyncTask has a progress dialog and dismiss it
// in an overrided cancel() method
task.execute();
}
private void handleOnBackButton() {
task.cancel(true);
}
Then all you need is to call handleOnBackButton()
when user presses back or home. You can do it using onKeyDown()
method.
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