Android-LruCache

2018-11-13  本文已影响0人  SimpleGk

LruCache,用于实现内存缓存,采用了Least Recently Used算法,即当缓存满时,优先删除最少使用的缓存。

int maxMemory=(int) (Runtime.getRuntime().maxMemory()/1024);//KB
        int cacheSize=maxMemory/8;
        mLruCache=new LruCache<String,Bitmap>(cacheSize){
            @Override
            protected int sizeOf(String key, Bitmap value) {
                if(Build.VERSION.SDK_INT>=19){
                    return value.getAllocationByteCount()/1024;
                }else {
                    return bitmap.getByteCount()/1024;
                }
            }
        };

maxMemory(),进程所能获取的最大内存,这里单位为KB,除8为缓存容量为内存的1/8,重写sizeOf方法,该方法是计算缓存对象大小。

if(Build.VERSION.SDK_INT>=19){
                    return value.getAllocationByteCount()/1024;
                }else  if (Build.VERSION.SDK_INT>=12){
                    return bitmap.getByteCount()/1024;
                }else{
                    return bitmap.getRowBytes()*bitmap.getHeight()/1024;
                }

mLruCache.put(key,bitmap);//添加缓存
mLruCache.get(key)//获取缓存
LruCache移除旧缓存会调用entryRemoved()方法,可以重新该方法完成一些资源回收工作

使用测试,下载图片的代码

URL url=new URL(path);
                            URL url=new URL(path);
                            InputStream inputStream=url.openStream();
                            bitmap= BitmapFactory.decodeStream(inputStream);
                            mLruCache.put(key,bitmap);
                            list.add(key);
                            inputStream.close();
上一篇 下一篇

猜你喜欢

热点阅读