Let's say I've two AsyncTask. AsyncTask_A and AsyncTask_B. I want to execute AsyncTask_B only when AsyncTask_A is totally finished. I know one that I could execute AsyncTask_B in AsyncTask_A's postExecute() method. But.. is there any better way?
Asked
Active
Viewed 381 times
0
-
this post may help you :http://stackoverflow.com/questions/7494515/android-can-i-chain-async-task-sequentially-starting-one-after-the-previous-as – Nibha Jain Aug 04 '14 at 05:01
-
This is already the default behavior if you're targeting Honeycomb or later - all `AsyncTask`s will be executed sequentially. – corsair992 Aug 04 '14 at 05:47
2 Answers
1
In this instance you should create a class that acts a singleton that will handle queuing of these tasks (i.e. a list of AsyncTasks within it) where it tracks if any are running, and if they are, queues them instead. Then within the postExecute() of these tasks, all should callback to the queue object to notify them that they are completed, and then within this callback it should then run the next AsyncTask.
This will allow you to:
- Call AsyncTaskA without always having to run AsyncTaskB (removing the hard dependency)
- Add more AsyncTasks down the track because the dependency on managing these tasks is on the queue object instead of within the AsyncTasks

Andrew Breen
- 685
- 3
- 11
-
Sorry, I don't fully understand that you wanna say cuz I'm dumb. Any example ? – Zin Win Htet Aug 04 '14 at 04:41
0
Queue<ASyncTask> q;
AsyncTask_A async_a;
AsyncTask_B async_b;
q.add(async_a);
q.add(async_b);
while(!q.empty)
{
AsyncTask task = q.pop();
task.execute();
while(task.isRunning())
{
Thread.sleep(SOME_MILLISECONDS) // You can use wait and notify here.instead of sleep
}
}

Changdeo Jadhav
- 706
- 9
- 23
-
-
Yeah right. I was just trying to give out pseudo code. Meant some flag which will decide if task is still running or finished. – Changdeo Jadhav Aug 04 '14 at 08:22
-
if(task.getStatus()==AsyncTask.Status.RUNNING) can be used. But it makes my app freeze. It seems the while will never stop. – Zin Win Htet Aug 04 '14 at 09:45