Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android AsynTask with progress dialog cancel

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

like image 489
Jovan Avatar asked Apr 01 '11 13:04

Jovan


2 Answers

    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.

like image 141
sharic19 Avatar answered Nov 12 '22 06:11

sharic19


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.

like image 9
Vladimir Ivanov Avatar answered Nov 12 '22 06:11

Vladimir Ivanov