-1

I have a doubt about asynctasks. In my application, i have two activities. The first activity as an async task that receives data, and in the second activities i have other asynctask to also receive data but also another async task that will send data. The problem is: When i go to the second activity, and i send data, i want the async task of the second activies receive that data, but it's the async task from the first activity that is receiving.

Anyone can help me finding a way to kill a async task when i change from one activity to another?

2 Answers2

0

Based on what I understood from your question, these might be helpful.

How to stop asynctask thread in android?

http://developer.android.com/reference/android/os/AsyncTask.html (read the "Cancelling a task" section).

Community
  • 1
  • 1
Supratim Haldar
  • 2,376
  • 3
  • 16
  • 26
0

An example from a runnning code.Let's say you have an async task object called loadApps (in my case). When you switch between activities, call:

 if (loadApps != null && loadApps.getStatus() == AsyncTask.Status.RUNNING) {
        loadApps.cancel(true);            
    }

And in your async task class in doInBackground method you need to check at some point (at the beginning or if there is loop in between iterations) for boolean isCanceled()

daxgirl
  • 762
  • 4
  • 10
  • Thanks a lot of your answer. Just another doubt, after checking the isCanceled(), what it's supposed to return. Can you give an example – Artur Oliveira May 10 '16 at 20:09
  • Well in my case it breaks the loop. In your case.. you need to find a way to return something (whatever is supposed to be the result... if is boolean... return false.. if is void... jut return). Most important thing to remember that once isCanceled is true, the task will not call onPostExecute method. It will call onCancelled method. Implement your logic there. If you have a listener, notify from there... if you need to cancel progress dialog... do it from there. It's a ui Thread callback. So you can work with ui elements like you do in onPostExecute method. – daxgirl May 10 '16 at 20:14