android image cache 图片缓存 异步 下载

自动判断从内存还是网络获取图片,缓存自动回收



import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
*
* @author yizhe
* @date 2012-6-13
*/
public class BitmapLoader {
// 内存缓存,SoftReference实现自动回收
private static HashMap<String, SoftReference<Bitmap>> imageCache = new HashMap<String, SoftReference<Bitmap>>();

/**
* 自动判断从内存还是从网络获取图片
*
* @param imageURL
* @return
*/
public static Bitmap loadBitmap(String imageURL) {
long time = new Date().getTime();
Comm.print(time + "--loadBitmap--" + imageURL);

Bitmap bm = null;
if (imageCache.containsKey(imageURL)) {// 从内存中获取
Comm.print(time + "--loadBitmap--from Cache");
SoftReference<Bitmap> reference = imageCache.get(imageURL);
bm = reference.get();
}
if (null == bm) {// 到网络下载
Comm.print(time + "--loadBitmap--from Net");
bm = getNetBitmap2(imageURL);
if (null != bm) {
imageCache.put(imageURL, new SoftReference<Bitmap>(bm)); // 保存到内存
}
}
if (null == bm) {
Comm.print(time + "--loadBitmap--false");
} else {
Comm.print(time + "--loadBitmap--true");
}
return bm;
}

// 从网络下载图片,方法2,本方法下载图片可能出现返回200状态但得到的bitmap为null的情况
private static Bitmap getNetBitmap(String imageURL) {
Bitmap bitmap = null;
try {
// 要下载的图片的地址,
URL url = new URL(imageURL);// 获取到路径
HttpURLConnection conn = (HttpURLConnection) url.openConnection();// http协议连接对象
conn.setRequestMethod("GET");// 这里是不能乱写的,详看API方法
conn.setConnectTimeout(9000);// 别超过10秒。
int state = conn.getResponseCode();
if (state == 200) {
Comm.print("--loadNetBitmap--" + state);
InputStream inputStream = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);
}
} catch (Exception e) {
Comm.print("--loadNetBitmap--e--" + e.toString());
}
return bitmap;
}

// 从网络下载图片,方法2,请使用本方法下载图片,
public static Bitmap getNetBitmap2(String imageURL) {
Bitmap bitmap = null;
try {
URL url = new URL(imageURL);// 获取到路径
HttpURLConnection conn = (HttpURLConnection) url.openConnection();// http协议连接对象
conn.setRequestMethod("GET");// 这里是不能乱写的,详看API方法
conn.setConnectTimeout(9000);// 别超过10秒。
int state = conn.getResponseCode();
if (state == 200) {
Comm.print("--loadNetBitmap--" + state);
int length = (int) conn.getContentLength();// 获取长度
InputStream is = conn.getInputStream();
if (length != -1) {
byte[] imgData = new byte[length];
byte[] temp = new byte[512];
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(temp)) > 0) {
System.arraycopy(temp, 0, imgData, destPos, readLen);
destPos += readLen;
}
bitmap = BitmapFactory.decodeByteArray(imgData, 0,
imgData.length);
}
}
} catch (Exception e) {
Comm.print("--loadNetBitmap--e--" + e.toString());
}
return bitmap;
}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值