Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ExecutorService with Android AsyncTask?

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.

like image 322
Akh Avatar asked Feb 29 '12 02:02

Akh


1 Answers

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.

like image 173
Nikolay Elenkov Avatar answered Oct 04 '22 16:10

Nikolay Elenkov