Alex Rivera | Logout

Android: Cancel Async Task

Asked 2011-05-18T02:13:27.460
64

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?

Edit
Report

2 Answers

9

create some member variables in your activity like

YourAsyncTask mTask;
Dialog mDialog;

use these for your dialog and task;

in onPause() simply call

if(mTask!=null) mTask.cancel(); 
if(mDialog!=null) mDialog.dismiss();
answered 2011-05-18T02:16:28.627
2

You can just ask for cancellation but not really terminate it. See this answer.

answered 2011-05-18T04:02:13.703

Your Answer