今天自己动手写一个图片加载器,在使用内存缓存时,从LruCache中得到的图片是一张黑的图片,而不是我存储进去的图片。
内存缓存的代码:
public class MemoryCache implements BaseCacheInterface {
final LruCache<String, Bitmap> mMemoryCache;
public MemoryCache() {
int memorySize = (int) (Runtime.getRuntime().maxMemory() / 1024);
int cacheSize = memorySize / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize){
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight() / 1024;
}
};
}
//存
@Override
public void add(String imageUrl, Bitmap bmp) {
Log.d("Http", "Memory cache add");
mMemoryCache.put(StringUtils.toHex(imageUrl), bmp) ;
}
//取
@Override
public Bitmap get(String imageUrl) {
Log.d("Http", "Memory cache get");
return mMemoryCache.get(StringUtils.toHex(imageUrl));
}
}
加载器中,从缓存中读取图片的代码:
//调用load加载图片到imageview
public void load(final String link, final ImageView imageView){
Log.d("Http", "load");
Bitmap bitmap = mCache.get(link); //从缓存里获取图片
if (bitmap != null){
imageView.setImageBitmap(mCache.get(link));
} else {
downloadBitmap(link, imageView); //缓存里没有,则从网络下载
}
Log.d("Http", "over");
}
private void downloadBitmap(final String link, final ImageView imageView){
imageView.setTag(link);
ImageThreadExecutor.getInstance().execute(new Runnable() { //封装的线程池
@Override
public void run() {
//imageHttpRequest为封装的Http请求类,downloadToInputStream()返回InputStream
final Bitmap bitmap = BitmapFactory.decodeStream(imageHttpRequest.downloadToInputStream(link));
if (imageView.getTag().equals(link) && bitmap != null){
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
mCache.add(link, bitmap);
}
}
});
}