0

I would like to cancel an Asynctask in android but I have a problem with my implementation :

My code is :

private class SynchroTask extends AsyncTask{ private volatile boolean running = true;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //INITIALIZATIONS
    }

    @Override
    protected Void doInBackground(Void... params) {
        while (running) {
            //TASK
        }

        return null;
    }

    @Override
    protected void onCancelled(){
        super.onCancelled();
        running = false;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        Intent intent = AccountAddActivity.getIntent(getActivity());
        startActivity(intent);
        getActivity().finish();
        }
    }
}

And :

mSynchroTask = new SynchroTask();


cancelButton.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {

                if (mSynchroTask != null && mSynchroTask.getStatus() != AsyncTask.Status.FINISHED){
                    HDCApplication.hdcAppManager.mSynchroManager.removeAllTask();
                    mSynchroTask.cancel(true);
                    mSynchroTask = null;

                }   
            }

        });
2
  • the "problem" is with HDCApplication.hdcAppManager.mSynchroManager.removeAllTask(); Commented Sep 3, 2012 at 19:47
  • when i do : mSynchroTask.cancel(true); I never pass in the onCancelled Commented Sep 3, 2012 at 19:50

2 Answers 2

2

That's half of implementation of what you have done

   mSynchroTask.cancel(true);

A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns.

This is what you are missing

To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)

Source : http://developer.android.com/reference/android/os/AsyncTask.html

Sign up to request clarification or add additional context in comments.

1 Comment

oh thank you, How to test the value of isCancelled periodically in the doinbackground
0
if (mSynchroTask != null && mSynchroTask.getStatus() != AsyncTask.Status.FINISHED){
                mSynchroTask.cancel(true);
                mSynchroTask = null;

                HDCApplication.hdcAppManager.mSynchroManager.removeAllTask();

            }  

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.