0
我正在使用LruCache來存儲位圖。使用緩存來存儲位圖
這是我運行的存儲位圖的異步任務。
new AsyncTask<Void, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(Void... args) {
String url = d.getImageUrl();
if (url != null && !url.equals("")) {
try {
LogUtils.log("getting image from cache");
Bitmap image = imageCache.getBitmapFromMemCache(url);
if (image == null) {
image = BitmapFactory.decodeStream(new URL(url)
.openConnection().getInputStream());
LogUtils.log("storing image to cache");
imageCache.addBitmapToMemoryCache(url, image);
} else {
LogUtils.log("got image from cache");
}
return image;
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(Bitmap image) {
if (holder.image != null) {
if (image != null) {
holder.image.setImageBitmap(image);
holder.image.setVisibility(View.VISIBLE);
}
}
}
}.execute();
這裏是我的緩存實現:
public class ImageCache {
private static ImageCache instance;
public static ImageCache getInstance(Context context) {
if (instance == null)
instance = new ImageCache(context);
return instance;
}
private LruCache<String, Bitmap> mMemoryCache;
private ImageCache(Context context) {
// Get memory class of this device, exceeding this amount will throw an
// OutOfMemory exception.
final int memClass = ((ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();
final int cacheSize = (1024 * 1024 * memClass)/8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in bytes rather than number
// of items.
return bitmap.getRowBytes() * bitmap.getHeight();
}
};
}
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
LogUtils.log("key: " + key);
if (getBitmapFromMemCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
}
public Bitmap getBitmapFromMemCache(String key) {
return mMemoryCache.get(key);
}
}
在我的表現我也有:
android:largeheap="true"
的問題是,在我的ListView ...當我向下滾動.. ..圖像從URL重新加載和代碼到達此行:
LogUtils.log("storing image to cache");
什麼可能導致此問題?
我會建議你使用這個庫,它下載,顯示和緩存圖像。沒有必要重新發明輪子。 https://github.com/nostra13/Android-Universal-Image-Loader – FWeigl
我遵循你的建議,使用時我也有同樣的問題:\t \t String url = d.getImageUrl(); \t \t ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(v.getContext())。 \t \t \t \t build(); \t \t ImageLoader imageLoader = ImageLoader.getInstance(); \t \t imageLoader.init(config); \t \t imageLoader.displayImage(「」,holder.image); \t \t imageLoader.displayImage(url,holder.image); – jimbob