Ashish Patel
Ashish Patel

Reputation: 41

How can I stop asynctask in android when back button is pressed?

I am running an AsyncTask and it is taking a little time to load. In that period of time, if I am pressing back button then it does not respond. It responds only after a few seconds. So how can I kill or pause or override AsyncTask to go back? Or is there any other way to do something similar?

if (mainContent != null) {
    mainContent.post(new Runnable() {
         @Override
         public void run() {
             Bitmap bmp = Utilities.getBitmapFromView(mainContent);
             BlurFilter blurFilter = new BlurFilter();
             Bitmap blurredBitmap = blurFilter.fastblur(bmp,1,65);
             asyncTask = new ConvertViews(blurredBitmap);
             asyncTask.execute();
         }
    });

My AsyncTask:

class ConvertViews extends AsyncTask<Void,Void,Void> {
        private Bitmap bmp;

        public ConvertViews(Bitmap bmp){
            this.bmp = bmp;
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                //Thread.sleep(200);
                if(mainViewDrawable == null) {
                    mainViewDrawable = new BitmapDrawable(getResources(), bmp);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }

My onBackPressed():

public void onBackPressed() {
    super.onBackPressed();
    asyncTask.cancel(true);
    finish();
}

Upvotes: 1

Views: 876

Answers (2)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

there is no way that you can stop a asynch task instantly.Every AsynchTask has a boolean flag property associated with it so if cancel_flag =True mean task has been canceled and there is a cancel() function which can be called on aasynchtask object like this

loginTask.cancel(true);

but all this cancel() function does is ,it will set a cancel boolean(flag ) property of asynch task to True so , you can check this property with isCancelled() function inside doInBackGround and do something ,like

protected Object doInBackground(Object... x) {
    while (/* condition */) {
      // work...
      if (isCancelled()) break;
    }
    return null;
 }

and if it is True then you can use break the loops(if you are doing a long task) or return to go quickly out of doInBackground and calling cancel() on asynchtask will skip the execution of onPostExecute().

and the other option is ,if you want to stop multiple running asynch task in background then calling cancel on each one can be tedious so in this case you can have a boolean flag in container class(of asynchtask) and skip the working inside asynchtask if the flag has been set to True ,like

protected Object doInBackground(Object... x) {
    while (/* condition */) {
      // work...
      if (container_asynch_running_flag) break;
    }
    return null;
 }

but make sure to also put a check in onpostExecute in this case because it won't stop the execution of onpost.

Upvotes: 2

Anton Malyshev
Anton Malyshev

Reputation: 8861

You can stop it instantly calling asyncTask.cancel(true).

But it is not recommended to do because it can lead to memory leaks. Better to call asyncTask.cancel(false) and exit from doInBackground function manually checking isCancelled() value as @Pavneet advised.

Upvotes: 0

Related Questions