Search code examples
androidasynchronoustaskback

Android: Cancel Async Task


I use an async task to upload an image and get some results.

While uploading the image I see a progress dialog, written in onPreExecute() method like this:

    protected void onPreExecute() { 
         uploadingDialog = new ProgressDialog(MyActivity.this); 
         uploadingDialog.setMessage("uploading"); 
         uploadingDialog.setCancelable(true);
         uploadingDialog.show();
    }

Ok when I press the back button, obviously the dialog disappears because of the setCancelable(true).

But (obviously) the async task doesn't stop.

So how can I fix this? I want to cancel both dialog and async task when I press the back button. Any ideas?


Solution

  • FOUND THE SOLUTION: I added an action listener before uploadingDialog.show() like this:

        uploadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
              public void onCancel(DialogInterface dialog) {
                  myTask.cancel(true);
                  //finish();
              }
        });
    

    That way when I press the back button, the above OnCancelListener cancels both dialog and task. Also you can add finish() if you want to finish the whole activity on back pressed. Remember to declare your async task as a variable like this:

        MyAsyncTask myTask=null;
    

    and execute your async task like this:

        myTask = new MyAsyncTask();
        myTask.execute();