Ricky Zheng
Ricky Zheng

Reputation: 1289

How to cancel the execution of a method when the "back" button is click in android

my data is load from the internet, so I use the AsynTask(). execute() method to open a progressDialog first, then load the data in the background. it works, however, sometimes it takes too long to load the data so I want to cancel loading, and here is the problem: when I click back button the dialog dismiss but after it finish loading at the background, it start to do whatever it supposed to do after loading, e.g. start a new intent. is there any way I can cancel the loading properly???

new GridViewAsyncTask().execute();
public class GridViewAsyncTask extends AsyncTask<Void, Void, Void> {
    private ProgressDialog myDialog;

    @Override
    protected void onPreExecute() {
        // show your dialog here
        myDialog = ProgressDialog.show(ScrollingTab.this, "Checking data",
                "Please wait...", true, true);

    }

    @Override
    protected Void doInBackground(Void... params) {
        // update your DB - it will run in a different thread
        loadingData();

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // hide your dialog here
        myDialog.dismiss();
}

Upvotes: 0

Views: 156

Answers (2)

yugidroid
yugidroid

Reputation: 6690

Declare your AsyncTask like asyncTask = new GridViewAsyncTask();

Then execute it as you did it before (asyncTask.execute();) and to cancel it:

asyncTask.cancel();

Add the onCanceled method to your AsyncTask class and override it. Perhaps to show a Log or something else!

@Override
protected Void onCancelled () {
    // Your Log here. Will be triggered when you hit cancell.
}

Upvotes: 1

Ron
Ron

Reputation: 24233

Call mAsycntask.cancel(); when you want to stop the task.

Then

@Override
protected Void doInBackground(Void... params) {
    // update your DB - it will run in a different thread

    /* load data  */
    ....
    if (isCancelled()) 
       return;
    /* continue loading data. */

    return null;
}

Documentation: http://developer.android.com/reference/android/os/AsyncTask.html#isCancelled()

Upvotes: 2

Related Questions