0

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

leo
  • 5
  • 3

4 Answers4

1

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

Community
  • 1
  • 1
Blaze Tama
  • 10,828
  • 13
  • 69
  • 129
0

You can use like:

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

    if(mAsyn.isCancelled()){
        mAsyn.cancel(true);
    }
Vibhor Chopra
  • 647
  • 4
  • 14
0

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.

Krunal Indrodiya
  • 782
  • 2
  • 7
  • 19
0

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");
sakis kaliakoudas
  • 2,039
  • 4
  • 31
  • 51