How to use ExecutorService with Android AsyncTask?
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.
Akh
Updated on June 04, 2022Comments
-
Akh almost 2 years
I need to execute a number of
AsyncTask
s 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
AsyncTask
s in Android. I am thinking of using aExecutorService
from the Java Concurrency package but I stuck becauseExecutorService
takes either Runnables or Callables ONLY. To establish my requirement I can use theExecutorService.invokeAll((Collection<? extends Callable<T>> tasks)
The
invokeAll()
method will return a list ofList<Future><V>>
only when all submitted tasks are completed and I can get my results for each task from its correspondingFuture
.All is well with
ExecutorService
expect for the fact that it doesn't acceptAsyncTask
.Is there any other way to use
AsyncTask
andExecutorService
or if you can please recommend a different approach.