javaandroidmultithreadingandroid-asynctaskandroid-handlerthread

download users profile pics from Facebook: AsyncTask or HandlerThread


I've a list of urls. Each url holds a differenct facebook user's profile pic.

I would like to download these pics and display them on the UI thread (on the screen).

I used new AsyncTask for each image and the images are displayed one by one.

doInBackground (background thread) returns the Bitmap:

InputStream in = new java.net.URL(imgUrl).openStream();
Bitmap bm = BitmapFactory.decodeStream(in);

onPostExecute (UI thread) will set the image bitmap for my members

  1. Is it the correct way to download the pics or I need to use Handlers?
  2. AsyncTask is chosen when users want to make changes on the UI while Handler is used to communicate between any 2 threads by messages. Is there any special difference? because it seems that I could use both attitudes.

Solution

  • Async Task is often the simplest way to work on a seperate thread than UI thread, but its not always the best one.

    My rule of thumb would be:

    If you are doing something isolated related to UI, for example downloading data to present in a list, go ahead and use AsyncTask.

    If you are doing multiple repeated tasks, for example downloading multiple images which are to be displayed in ImageViews (like downloading thumbnails) upon download, use a task queue with Handler.

    EDIT:

    As @Thecave3 pointed out it is best to let the image loading libraries do the loading for you. Picasso and Glide are suitable choices. They even provide download and error placeholders as optional features.