Android AsynTask with progress dialog cancel

2019-03-18 01:32发布

问题:

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

回答1:

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.



回答2:

    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.



回答3:

You just have to set your ProgressDialog cancelable. And it will disappear when you click "Back" button. Like This :

dialog.setCancelable(true);

You have to override onBackPressed to dismiss the ProgressDialog as well as cancel AsyncTask

@Override
public void onBackPressed() {
YourAsyncTaskObject.cancel(true);
YourProgressDialog.dismiss();
return;
}


回答4:

I have found that the back button event is consumed the ProgressDialog that is 'show'n, so the Activity does not get to act on the cancel. I had to add a listener to the dialog:

mProgress = ProgressDialog
        .show(this, getText(R.string.progress_title),
        getText(R.string.progressing), true, true,
        new OnCancelListener() {
            public void onCancel(DialogInterface pd) {
                handleOnBackButton();
            }
        });         

Nevermind.

I found it much cleaner to use the Activity's dialog management and add an onDismissListener during onCreateDialog. The dismiss listener can cancel the task. No need to hold a reference to the dialog and that is the only place we need to listen for user cancel.