这段时间看见很多人做listview(比如模拟新浪客户端)用到这一个图片下载的类,我也不知道这个类到底是哪个大神写的,反正我使用这个类的时候接手别人的,刚开始,感觉这个类写的听不错,比我写的AsyncImageTask.java好多了,先说说我最开始写的吧,也算是抛砖引玉:
public class AsyncImageTask extends AsyncTask<String, Void, InputStream>{
private ImageView imageView;
public AsyncImageTask(ImageView imageView){
this.imageView = imageView;
}
@Override
protected InputStream doInBackground(String... params) {
InputStream inputStream = null;
try {
URL url = new URL(params[0]);
inputStream = url.openStream();
} catch (IOException e) {
e.printStackTrace();
}
return inputStream;
}
@Override
protected void onPostExecute(InputStream result) {
if(imageView!=null && result!=null){
Bitmap bmp = BitmapFactory.decodeStream(result);
imageView.setImageBitmap(bmp);
}
super.onPostExecute(result);
}
}
我写完的时候感觉就挺别扭的的,能满足我当时的需求,也就这么用了(有哪位高手指点其中的缺点哈),这个类里,我们只需要传入显示图片的ImageView和图片的网络地址,当图片下载完成后,显示出来就可以了。后来我的主管把它换掉了,用了AsyncImageLoader.java这个类,仔细看看,写的确实不错。不说废话,先把这个类的代码贴上去(AsyncImageLoader.java):
public class AsyncImageLoader {
private HashMap<String, SoftReference<Drawable>> imageCache;
public AsyncImageLoader() {
imageCache = new HashMap<String, SoftReference<Drawable>>();
}
public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback) {
if (imageCache.containsKey(imageUrl)) {
SoftReference<Drawable> softReference = imageCache.get(imageUrl);
Drawable drawable = softReference.get();
if (drawable != null) {
return drawable;
}
}
final Handler handler = new Handler() {
public void handleMessage(Message message) {
imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
}
};
new Thread() {
@Override
public void run() {
Drawable drawable = loadImageFromUrl(imageUrl);
imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
Message message = handler.obtainMessage(0, drawable);
handler.sendMessage(message);
}
}.start();
return null;
}
public static Drawable loadImageFromUrl(String url) {
URL m;
InputStream i = null;
try {
m = new URL(url);
i = (InputStream) m.getContent();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Drawable d = Drawable.createFromStream(i, "src");
return d;
}
public interface ImageCallback {
public void imageLoaded(Drawable imageDrawable, String imageUrl);
}
}