Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

Cancel AsyncTask in Android

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;

                }   
            }

        });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...