Created
August 26, 2013 04:47
-
-
Save dittos/6338178 to your computer and use it in GitHub Desktop.
LruCache-based BitmapCache for Volley
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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