Android provides LRU cache, that is to evict the least recently used item from the data.
https://developer.android.com/reference/android/util/LruCache.html
1. The size of the cache can be adjusted like the following (depends on the purpose of having cache and the resolution of the devices):
// Cache Size ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); int availableMemoryInBytes = am.getMemoryClass() * 1024 * 1024; // Need to adjust size LruCache bitmapCache = new LruCache(availableMemoryInBytes / 8); 
2. In the example we need to override sizeOf() methods with bitmap size
public class MyCache extends LruCache(String, Bitmap) {
    @Override
    protected int sizeOf(String Key, Bitmap value) {
        // return the size of the in-memory bitmap
        // counted against maxSizeBytes
        return value.getByteCount();
    }
    ...
}      
3. The usage of the LRU cache:
Bitmap bitmap = mCache.get(filename);
if (bitmap == null) {
    bitmap = BitmapFactory.decodeFile(filename);
    mCache.put(filename, bitmap );
}
댓글 없음:
댓글 쓰기