异步加载图片
来源:互联网 发布:八字预测全息论淘宝 编辑:程序博客网 时间:2024/06/07 01:37
使用java软缓冲和线程异步操作
import java.io.IOException;
import java.io.InputStream;import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
public class AsyncImageLoader {
private HashMap<String, SoftReference<Drawable>> imageCache;
public AsyncImageLoader() {
imageCache = new HashMap<String, SoftReference<Drawable>>();
}
public Drawable loadDrawable(final String imageUrl,
final ImageView imageView, 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, imageView,
imageUrl);
}
};
new Thread() {
@Override
public void run() {
Drawable drawable = loadDrawable(imageUrl);
imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
Message message = handler.obtainMessage(0, drawable);
handler.sendMessage(message);
}
}.start();
return null;
}
public Drawable loadDrawable(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, ImageView imageView,
String imageUrl);
}
}
调用方法:
Drawable drawable = new AsyncImageLoader().loadDrawable(picUrl, pImageView, new ImageCallback()
{
public void imageLoaded(Drawable imageDrawable, ImageView imageView, String imageUrl)
{
imageView.setImageDrawable(imageDrawable);
}
});
if (drawable!=null)
{
pImageView.setImageDrawable(drawable);
}
}
注意 : pImageView是你要显示图片的ImageView的对象。
- 异步加载图片
- 异步加载图片
- ajax异步加载图片
- android异步加载图片
- 异步图片加载实例
- android 异步加载图片
- 图片异步加载
- list 异步加载图片
- 异步加载本地 图片
- UITableView 异步加载图片
- android异步加载图片
- inputstream 异步加载图片
- iPhone 异步加载图片
- android异步加载图片
- 图片的异步加载
- 异步图片加载控件
- uiimageview 异步加载图片
- UITableView异步加载图片
- 浅析CPU中断技术
- Android 中使用ListView和CheckBox进行批量操作
- Hibernate in action阅读笔记-吵吵冷饭-持久化对象
- ios 解析xml 并且运用了字典和可变数组存放数据
- SQL Server高级内容之子查询和表链接
- 异步加载图片
- makefile 文件模版
- 对RESTful Web API的理解与设计思路
- Shell 编程11(IO重定向)
- 人云我亦云
- 小程序教你深刻理解&&与&, ||和|
- java键盘输入
- TCP 编程。
- JUnit测试中setup()和teardown()方法