Android 加载图片并存放在缓存中

package com.easaa.image;


import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;


import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;


public class AsyncImageLoader {

/**
* SoftReference 于 WeakReference 的特性基本一致,都是放在MAP中
*  最大的区别在于 SoftReference 会尽可能长的保留引用直到 JVM 内存不足时才会被回收(虚拟机保证),
*   这一特性使得 SoftReference 非常适合缓存应用 
*   
*   利用多线程实现异步加载
*/

private Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();


/**
* 加载图片,传入一个URL,
* @param imageUrl
* @param callback
* @return
*/
public Drawable loadDrawable(final String imageUrl,
final ImageCallback callback) {
if (imageCache.containsKey(imageUrl)) {
SoftReference<Drawable> softReference = imageCache.get(imageUrl);
if (softReference.get() != null) {
return softReference.get();
}
}
//采用异步消息
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
callback.imageLoaded((Drawable) msg.obj, imageUrl);
}
};
//开启一个线程
new Thread() {
public void run() {
Drawable drawable = loadImageFromUrl(imageUrl);
imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
handler.sendMessage(handler.obtainMessage(0, drawable));
};
}.start();
return null;
}


//传入一个URL
protected Drawable loadImageFromUrl(String imageUrl) {
Drawable drawableSS = null;
try {
drawableSS = Drawable
.createFromStream(
new URL(
"http://a222.photo.store.qq.com/psb?/2267082e-b0b6-43c6-8da8-ba3f726744e6/4nJy.Jpl1*pYr7GvDG1IlPfFooUkupkJd9RAFzwg0aU!/a/YbdJYIQUJwAAYj.dVYQSKAAA")
.openStream(), "src");
return Drawable.createFromStream(new URL(imageUrl).openStream(),
"src");
} catch (Exception e) {
return drawableSS;
// throw new RuntimeException(e);
}
}


//定义一个接品
public interface ImageCallback {
public void imageLoaded(Drawable imageDrawable, String imageUrl);
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值