美文网首页
Android-LruCache

Android-LruCache

作者: SimpleGk | 来源:发表于2018-11-13 16:37 被阅读0次

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();

相关文章

  • Android-LruCache

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

  • Android-LruCache

    LruCache介绍 LruCache 顾名思义就是使用LRU缓存策略的缓存,那么LRU是什么呢? 最近最少使用到...

网友评论

      本文标题:Android-LruCache

      本文链接:https://www.haomeiwen.com/subject/fdelfqtx.html