How to use ExecutorService with Android AsyncTask?

Akh picture Akh · Feb 29, 2012 · Viewed 11.4k times · Source

I need to execute a number of AsyncTasks and then gather all their results, consolidate and then return the final result to my user.

I am looking at a way to manage multiple AsyncTasks in Android. I am thinking of using a ExecutorService from the Java Concurrency package but I stuck because ExecutorService takes either Runnables or Callables ONLY. To establish my requirement I can use the

ExecutorService.invokeAll((Collection<? extends Callable<T>> tasks)

The invokeAll() method will return a list of List<Future><V>> only when all submitted tasks are completed and I can get my results for each task from its corresponding Future.

All is well with ExecutorService expect for the fact that it doesn't accept AsyncTask.

Is there any other way to use AsyncTask and ExecutorService or if you can please recommend a different approach.

Answer

Nikolay Elenkov picture Nikolay Elenkov · Feb 29, 2012

Create an AsyncTask and start your threads from doInBackground(). When they are done, collect, consolidate, etc. the data and return it. Then you can use it in onPostExecute to update the UI. Starting too many thread will consume memory, so you should consider whether they really need to run in parallel.