Check if all AsyncTasks have finished

emeraldhieu picture emeraldhieu · Aug 3, 2011 · Viewed 23k times · Source

I have 3 AsyncTasks and 1 ProgressBar. I want when any of task executes, the progress bar is visible and when all of them finish, the progress bar is invisible.

In Java, there is ExecutorService::isTerminated to check if all runnables finished but Android doesn't have it.

Update: 3 tasks execute at the same time.

Figure. enter image description here

Answer

Mojo Risin picture Mojo Risin · Aug 3, 2011

Nice graphic. But I am afraid there is no build in mechanism for this. You'll have to implement it by yourself. There are few solutions you could use -

  1. Keep a reference to all 3 task. When task finishes check if the other two tasks are finished too, if yes than close the progress dialog if no wait for some other task to finish and check again. Make sure you free the references when you're done.
  2. If you don't want to keep a reference store a counter. When the task finishes, increment the counter and check if it's equal to 3. If all tasks finished and you are done. If you implement this make sure to synchronized the access to the counter.