Adam Matan
Adam Matan

Reputation: 136231

Android: HTTP requests in AsyncTask are not concurrent

I'm writing a fan app for my local cinematheque, which shows the screening calendar for the next few days. The per-day film list is retrieved using a parametrized HTTP call from the site (The answer contains Hebrew, so if you clicked the link and got some Gibberish it's probably OK).

The app displays the schedule for the next eight days, so It makes 8 calls with per-day schedule request.

private class GetMoviesTask extends AsyncTask<Integer, Void, List<Film>>

doInBackground() retrieves the list of films per day, and onPostExecute() updates the interface.

The AsyncTask is called from MainActivity.onCreate():

for (int i=0; i<NUMBER_OF_DAYS_TO_VIEW; i++){
    new GetMoviesTask().execute(i);
}

The problem is that AsyncTask is not executed concurrently. The days are slowly loaded one after another, which is painfully slow:

enter image description here

enter image description here

enter image description here

What's the best way to start these AsyncCalls concurrently?

Upvotes: 4

Views: 3212

Answers (2)

Giulio Piancastelli
Giulio Piancastelli

Reputation: 15807

AsyncTask has been known to hit a regression in Android 4.x, where the system executes them one at a time instead of executing them concurrently as it did since Android 1.6. This is by design: basically, on newer platforms, you can revert to the old concurrent behaviour by calling executeOnExecutor() instead of execute(). Mark Murphy (known as Commonsware on StackOverflow) has all the details sorted on his blog.

Upvotes: 12

Serdar Dogruyol
Serdar Dogruyol

Reputation: 5157

Basically AsyncTask only creates one thread for you which runs on the background.

You can achieve what you want in two ways.

  • Firstly you can create separate AsyncTasks for each of the operations.
  • Secondly by creating multiple threads in your doInBackground method and making concurrent requests and processes.After that you can notify your UI by publishing those to onProgressUpdate or onPostExecute.

Check this

android asynctask with threading

Upvotes: 0

Related Questions