0

I have an application that has a MapView. When user zooms or pans MapView, I execute a new instance of an AsyncTask to fetch MapView's data from server.

Assume that user pans map and we trigger async task to fetch map's data, before getting all data and updating map, user moves map again and a second async task will trigger. If the second async task finishes before first async task, it will update map, but after finishing first async task, mapview will be updated again and will show wrong data to user.

I want to know is there a way to stop (cancel) running async task and execute another one? If yes, how?

Chathuranga Chandrasekara
  • 20,548
  • 30
  • 97
  • 138
Ali Behzadian Nejad
  • 8,804
  • 8
  • 56
  • 106
  • check this [thread](http://stackoverflow.com/questions/12236899/how-to-check-if-async-task-is-already-running) – Alejandro Cumpa Feb 06 '14 at 14:51
  • That way I have the first AsyncTask running to the end and after finishing that task, I can run it again. I want to *cancel* previous one and then start a new task. – Ali Behzadian Nejad Feb 06 '14 at 14:59
  • 1
    Just use `.cancel(true)` as says in the [documentation](http://developer.android.com/reference/android/os/AsyncTask.html) – Alejandro Cumpa Feb 06 '14 at 15:02
  • 1
    You have call the cancel on the `asyntask` to cancel it. It meant that control wont go in the `onPostExecute(result)` if you have cancelled it when control is in `doInBackGround(..)` – Ajay S Feb 06 '14 at 15:06
  • You have to use yourasynctask.cancel(true); But in your doInBackground() method, you have to check periodically if the asynctask is canceled with the method.... this.isCanceled(); you cant"kill" an asynctask. – Cocorico Feb 06 '14 at 16:15
  • @TGMCians Post your comment as an answer, so I can accept it! Thank you! – Ali Behzadian Nejad Feb 06 '14 at 16:24

1 Answers1

0

You have to call the cancel on the AsynTask to cancel it.

It meant that control wont go in the onPostExecute(result) if you have cancelled it when control is in doInBackGround(..)

and you have to check that your asynctask has cancelled or not. You can do this isCancelled()

See here : http://developer.android.com/reference/android/os/AsyncTask.html#cancel(boolean)

See here : http://developer.android.com/reference/android/os/AsyncTask.html#isCancelled()

Ajay S
  • 48,003
  • 27
  • 91
  • 111