Android 图片资源的异步加载2

public class AsyncImageLoader {


private HashMap<String, SoftReference<Bitmap>> imageCache;
private static AsyncImageLoader asyncImageLoader;


public AsyncImageLoader() {
imageCache = new HashMap<String, SoftReference<Bitmap>>();
}


/**
* @return 得到类实例
*/
public static AsyncImageLoader getInstance() {
if (asyncImageLoader == null) {
asyncImageLoader = new AsyncImageLoader();
}
return asyncImageLoader;
}


/**
* @param imageUrl
*            图片url
* @param imageCallback
*            回调函数
* @return 图片
*/
public Bitmap loadDrawable(final String imageUrl,
final ImageCallback imageCallback) {
if (imageCache.containsKey(imageUrl)) {
SoftReference<Bitmap> softReference = imageCache.get(imageUrl);
Bitmap bitmap = softReference.get();
if (bitmap != null) {
return bitmap;
}
}
final Handler handler = new Handler() {
public void handleMessage(Message message) {
imageCallback.imageLoaded((Bitmap) message.obj, imageUrl);
}
};
new Thread() {
@Override
public void run() {
Bitmap bitmap = loadImageFromUrl(imageUrl);
imageCache.put(imageUrl, new SoftReference<Bitmap>(bitmap));
Message message = handler.obtainMessage(0, bitmap);
handler.sendMessage(message);
}
}.start();
return null;
}


/**
* @param url
*            图片url
* @return 下载到的图片
*/
public static Bitmap loadImageFromUrl(String url) {
URL m;
InputStream i = null;
try {
m = new URL(url);
       HttpURLConnection conn = (HttpURLConnection) m.openConnection();   
       conn.setConnectTimeout(30 * 1000);   
       conn.setRequestMethod("GET");   
       i = conn.getInputStream();  

} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(i);
// Drawable d = Drawable.createFromStream(i, "src");
return bitmap;
}


public interface ImageCallback {
public void imageLoaded(Bitmap imageBitmap, String imageUrl);
}


}

你可能感兴趣的:(java,android,ListView,imageview,asynchronous)