Android: Image cache strategy and memory cache size

后端 未结 3 2109
清歌不尽
清歌不尽 2021-02-05 22:01

I\'m implementing an image cache system for caching downloaded image.

My strategy is based upon two-level cache: Memory-level and disk-level.

My class is very si

3条回答
  •  死守一世寂寞
    2021-02-05 22:01

    I've been looking into different caching mechanisms for my scaled bitmaps, both memory and disk cache examples. The examples where to complex for my needs, so I ended up making my own bitmap memory cache using LruCache. You can look at a working code-example here or use this code:

    Memory Cache:

    public class Cache {
        private static LruCache bitmaps = new BitmapLruCache();
    
        public static Bitmap get(int drawableId){
            Bitmap bitmap = bitmaps.get(drawableId);
            if(bitmap != null){
                return bitmap;  
            } else {
                bitmap = SpriteUtil.createScaledBitmap(drawableId);
                bitmaps.put(drawableId, bitmap);
                return bitmap;
            }
        }
    }
    

    BitmapLruCache:

    public class BitmapLruCache extends LruCache {
        private final static int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        private final static int cacheSize = maxMemory / 2;
    
        public BitmapLruCache() {
            super(cacheSize);
        }
    
        @Override
        protected int sizeOf(Integer key, Bitmap bitmap) {
            // The cache size will be measured in kilobytes rather than number of items.
            return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
        }
    }
    

提交回复
热议问题