leo
leo

Reputation: 5

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();

Upvotes: 0

Views: 589

Answers (4)

sakis kaliakoudas
sakis kaliakoudas

Reputation: 2099

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");

Upvotes: 0

Krunal Indrodiya
Krunal Indrodiya

Reputation: 792

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.

Upvotes: 0

Vibhor Chopra
Vibhor Chopra

Reputation: 657

You can use like:

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

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

Upvotes: 0

Blaze Tama
Blaze Tama

Reputation: 10948

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

Upvotes: 1

Related Questions