1

I made the AsyncTask to load images for my RecyclerView. It has method downloadImage() which I call every time at ViewHolder. So for each image it should create new AsyncTask? I can't figure out if it download parallel or sequentially. (I can't use libraries, all must be custom)

private static class DownloadImage extends AsyncTask<String, Void, Bitmap> {

    private ImageView mBitmapImage;

    DownloadImage(ImageView imageView) {
        mBitmapImage = imageView;
    }

    @Override
    protected Bitmap doInBackground(String... strings) {
        String url = strings[0];
        Bitmap bitmapImage = null;
        InputStream in = null;

        try {
            in = new URL(url).openStream();
            bitmapImage = BitmapFactory.decodeStream(in);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bitmapImage;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        if (result != null) {
            mBitmapImage.setImageBitmap(result);
        } else {
            mBitmapImage.setImageResource(R.drawable.loading_movie);
        }
    }
}

public static void downloadImage(String imageLocation, ImageView imageView) {
    new DownloadImage(imageView).execute(MOVIE_POSTER_URL_REQUEST + imageLocation);
}

In adapter I call it like this:

void bindMovie(Movie movie) {
        mMovie = movie;
        mMovieTitle.setText(movie.getTitle());
        mDescription.setText(movie.getOverview());
        downloadImage(movie.getPosterPath(), mPoster);
    }
VolodymyrH
  • 1,927
  • 2
  • 18
  • 47

2 Answers2

2

It really depends on the version of Android system.

But if you want to be sure to execute tasks in parallel, use this (from support v.4 library): AsyncTaskCompat.executeParallel(task, params);

In-depth explanation (see the accepted answer): Running multiple AsyncTasks at the same time -- not possible?

UPDATE:

As you fairly stated, AsyncTaskCompat.executeParallel(task, params); is now deprecated in API 26, though i couldn't find an explanation why.

So, as the docs are saying, instead you should use asyncTask.executeOnExecutor(task, params);

To achieve parallel execution:

asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);

This method is typically used with THREAD_POOL_EXECUTOR to allow multiple tasks to run in parallel on a pool of threads managed by AsyncTask, however you can also use your own Executor for custom behavior.

Kirill Starostin
  • 868
  • 1
  • 7
  • 16
1

Do images with AsyncTask download parallel or sequentially?

For Honeycomb and up, default is a serial executor, which executes tasks one by one. But you can pass a ThreadPoolExecutor for execution:

Darish
  • 11,032
  • 5
  • 50
  • 70