I'm developing an app that requires multiple files being downloaded simultaneously. I am creating an AsyncTask
with its own HttpClient
for each file, but the next file only starts downloading after the previous one finished.
Might it be a server-side issue?
It is because AsyncTask management changed in Honeycomb . Previously if you started i.e. 3 AsyncTasks, these were running simultaneously. Since HC, if your targetSdk
is set to 12
or higher, these are queued and executed one by one (see this discussion). To work that around start your AsyncTasks that way:
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
instead of:
task.execute(params);
If you target also older Androids, you need conditional code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
} else {
task.execute(params);
}
or wrap it in a separate helper class:
public class Utils {
public static <P, T extends AsyncTask<P, ?, ?>> void executeAsyncTask(T task) {
executeAsyncTask(task, (P[]) null);
}
@SuppressLint("NewApi")
public static <P, T extends AsyncTask<P, ?, ?>> void executeAsyncTask(T task, P... params) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
} else {
task.execute(params);
}
}
}
and usage would be i.e.:
Utils.executeAsyncTask( new MyAsyncTask() );
When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution. Source
So depending on the version AsyncTask would not execute in parallel. For tasks like file download you should use thread pool using Executor
or you can use executeOnExecutor method..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With