Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simultaneous HttpClient request using multiple AsyncTasks

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?

like image 979
João G. Avatar asked Nov 19 '12 17:11

João G.


2 Answers

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() );
like image 55
Marcin Orlowski Avatar answered Nov 18 '22 22:11

Marcin Orlowski


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..

like image 45
Praful Bhatnagar Avatar answered Nov 18 '22 23:11

Praful Bhatnagar