12

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.

Simon Forsberg
  • 13,086
  • 10
  • 64
  • 108
Akh
  • 5,961
  • 14
  • 53
  • 82
  • 1
    Good thing is [AsyncTask](http://developer.android.com/reference/android/os/AsyncTask.html) has method executeOnExecutor(), bad thing is it is only available since API Level 11 – yorkw Feb 29 '12 at 02:57
  • Any references on how to use executeOnExecutor ? Moreover this feature is available from HoneyComb(API Level 11) but my app's minSDK is 4. – Akh Feb 29 '12 at 19:13
  • 1
    If you insist, check out my answer [here](http://stackoverflow.com/questions/7211684/asynctask-executeonexecutor-before-api-level-11/9509184#9509184). – yorkw Mar 01 '12 at 01:03

1 Answers1

2

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.

Nikolay Elenkov
  • 52,576
  • 10
  • 84
  • 84
  • AsyncTask itself has a pool of threads inside it. Can we use this pool to run multiple tasks instead me creating another one? – Akh Feb 29 '12 at 19:14
  • 1
    Not directly. As for `executeOnExecutor()`, the purpose of this method is to make it possible to execute multiple `AsyncTask`'s simultaneously, since the internal one can only execute one `AsyncTask` at a time (Honeycomb and later). What that means is that if you start two `AsyncTask`s more or less at the same time, the second will wait for the first to finish before it starts. If you need to do somthing more complicated, you don't have to use an `AsyncTask`, just your threading code as usual and use a Handler to notify the UI when you get the results. – Nikolay Elenkov Mar 01 '12 at 00:45
  • It is not TRUE that "What that means is that if you start two AsyncTasks more or less at the same time, the second will wait for the first to finish before it starts" – Zou Jun 28 '17 at 05:44
  • You can use AsyncTask.executeOnExecutor for multiThread purpose. – Zou Jun 28 '17 at 05:51