Asynchronously fetching images from Internet in Android

Here is a small class I wrote for Android, for loading pictures from the network in the background.

Not much, but quite handy.

import java.io.IOException;
import java.net.URL;
import java.net.HttpURLConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class AsyncImageLoader extends Thread {
    interface AsyncImageCallback {
        /** @brief Called by an AsyncImageLoader upon request completion.
          * @param url Same URL as the one passed to the AsyncImageLoader constructor.
          * @param bm A Bitmap object, or null on failure.
          */
        void onImageReceived(String url, Bitmap bm);
    }
    /** @brief Start an asynchronous image fetch operation.
      * @param url The URL of the remote picture.
      * @param cb The AsyncImageCallback object you want to be notified the operation completes.
      */
    public AsyncImageLoader(String url, AsyncImageCallback cb) {
        super();
        mURL=url;
        mCallback=cb;
        start();
    }
    public void run() {
        try {
            HttpURLConnection conn = (HttpURLConnection)(new URL(mURL)).openConnection();
            conn.setDoInput(true);
            conn.connect();
            mCallback.onImageReceived(mURL,BitmapFactory.decodeStream(conn.getInputStream()));
        } catch (IOException e) {
            mCallback.onImageReceived(mURL,null);
        }
    }
    private String mURL;
    private AsyncImageCallback mCallback;
}

Sample usage:

public class MyClass implements AsyncImageLoader.AsyncImageCallback {
    void onImageReceived(String url, Bitmap bm) {
        if (bm==null) {
            System.err.println("Could not load picture '"+url+"'!");
        }
        else if ("http://somewhere.net/foo.png".equals(url)) {
            paintFoo(bm);
        }
    }
    void someFunction() {
        new AsyncImageLoader("http://somewhere.net/foo.png", this);
    }
}
Powered by Blogger.