简体   繁体   中英

how to terminate AsyncTask in Android?

I'm currently have an Android application with 3 activities.

Main activity:

Constantly polling a Xml file using AsyncTask and update UI using onPostExecute.

The AsyncTask is loop by:

Handler.postDelayed(runnableCode, Poll_internval);

Second Activity:

Does the same thing, pulling Xml using another AsyncTask and update UI using onPostExecute.

loop by :

Handler.postDelayed(runnableCode, Poll_internval);

How should i kill the AsyncTask as it is constantly looping?

Would like to kill it when ending this activity with finish();

There is no way to cancel the AsyncTask , even with cancel method.

You need to implement your logic for canceling the task manually, see this link :

How to completly kill/remove/delete/stop an AsyncTask in Android

You can use like:

Asyn mAsyn = new Asyn();
    mAsyn.execute();

    if(mAsyn.isCancelled()){
        mAsyn.cancel(true);
    }

There is provision, you can remove async task in call back in handler, there is method

handler.removeCallbacks(runnable);

In Asynctask there is status, you have to develop logic and check status code.

AsyncTask statuc

In my project, i have same condition and i developed this kind of logic, it work in my code. please check it.

Have a look at the androidannotations framework, that has support for running async tasks and also cancelling them. You can checkout the details here:

https://github.com/excilys/androidannotations/wiki/WorkingWithThreads#background]

Basically, all you need to do is annotate the method that needs to run in another thread with

@Background(id="cancellable_task")
void someCancellableBackground(String aParam, long anotherParam) {
    [...]
}

where "id" is the id of the new thread. Then, to cancel it you just call

BackgroundExecutor.cancelAll("id");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM