Skip to content

Instantly share code, notes, and snippets.

@dittos
Created August 26, 2013 04:47
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dittos/6338178 to your computer and use it in GitHub Desktop.
Save dittos/6338178 to your computer and use it in GitHub Desktop.
LruCache-based BitmapCache for Volley
package com.gae9.android.util;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.toolbox.ImageLoader.ImageCache;
public class BitmapCache implements ImageCache {
private LruCache<String, Bitmap> mMemoryCache;
private static int getBitmapByteCount(Bitmap bitmap) {
return bitmap.getRowBytes() * bitmap.getHeight();
}
public BitmapCache(int maxMemoryCacheSizeInBytes) {
mMemoryCache = new LruCache<String, Bitmap>(maxMemoryCacheSizeInBytes) {
protected int sizeOf(String key, Bitmap value) {
return getBitmapByteCount(value);
}
};
}
public Bitmap getBitmap(String url) {
return mMemoryCache.get(url);
}
public void putBitmap(String url, Bitmap bitmap) {
mMemoryCache.put(url, bitmap);
}
private static long getHeapSize() {
return Runtime.getRuntime().maxMemory();
}
public static int detectCacheSize() {
final float DEFAULT_MEMORY_CACHE_HEAP_RATIO = 1f / 8f;
final float MAX_MEMORY_CACHE_HEAP_RATIO = 0.75f;
final float percentageOfHeap = DEFAULT_MEMORY_CACHE_HEAP_RATIO;
int size = Math
.round(getHeapSize() * Math.min(percentageOfHeap, MAX_MEMORY_CACHE_HEAP_RATIO));
return size;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment