Android 异步加载图片的实例代码
异步加载图片的主要流程是进行判断缓存中是否存在图片,如果存在则直接返回,如果不存在则进行下载并进行缓存。
以下是建立一个异步下载类:
/**
* user: tom
* date: 13-5-13
* time: 下午8:07
*/
public class asnycimageloader {
//定义一个hashmap进行存放缓存的image key为string value为一个弱引用的一个资源文件
// 图片 为了方便java的回收
private map<string, softreference<drawable>> imagecache = null;
public asnycimageloader() {
imagecache = new hashmap<string, softreference<drawable>>();
}
/**
* 加载图片
* <p>imageurl为下载资源的url,
* imagecallback当缓存中不存在相关图片时时行网络下载
* 在多线程下要使用handler进行操作ui 利用回调接口的方式进行更新ui
* </p>
* @param imageurl
* @param callback
* @return
*/
public drawable loaddrawable(final string imageurl, final imagecallback callback) {
//进行判断imagecache中是否存在缓存图片
if (imagecache.containskey(imageurl)) {
softreference<drawable> softreference = imagecache.get(imageurl);
if (softreference.get() != null) {
return softreference.get();
}
}
//定义操作ui的handler
final handler handler = new handler() {
@override
public void handlemessage(message msg) {
callback.imageloaded((drawable) msg.obj);
}
};
new thread(new runnable() {
@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;
}
//根据url地址进行获取资源
protected drawable loadimagefromurl(string imageurl) {
try {
return drawable.createfromstream(new url(imageurl).openstream(), "src");
} catch (exception e) {
throw new runtimeexception();
}
}
//回调接口
public interface imagecallback {
public abstract void imageloaded(drawable drawable);
}
}
主activity:
/**
* user: tom
* date: 13-5-13
* time: 下午8:33
*/
public class loadimage extends activity {
private asnycimageloader loader = null;
public void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.loadimages);
loader = new asnycimageloader();
loadimage("//www.jb51.net/images/icon-partners.png", r.id.image1);
loadimage("//www.jb51.net/images/icon-dev.png", r.id.image2);
loadimage("http://pic28.jb51.net/20130421/12302174_231210305323_2.jpg", r.id.image3);
}
public void loadimage(string url, int id) {
final imageview imageview = (imageview) findviewbyid(id);
drawable cacheimage = loader.loaddrawable(url, new asnycimageloader.imagecallback() {
@override
public void imageloaded(drawable drawable) {
imageview.setimagedrawable(drawable);
}
});
if (cacheimage != null) {
imageview.setimagedrawable(cacheimage);
}
}
}