------

[ AD ] Port Monitor ( Try to use a Best WebSite Monitoring Tool )

------

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);
    }
}


 

'0.일반개발' 카테고리의 다른 글

XML 파싱 Parsing Parser 파서  (0) 2010.09.16
이클립스 멤버 변수 / 멤버 함수 생성기  (0) 2010.09.16
안드로이드 ( 내부 layout 모듈 xml )  (0) 2010.09.16
EditText  (0) 2010.09.15
EditText  (0) 2010.09.15

+ Recent posts