为什么选择LruCache做图片缓存?而不是软引用或弱引用
1:因为LruCache当缓存的图片达到了预先设定的值的时候,那么近期使用次数最少的图片就会被回收掉(这个值可以由我们来设置)
2:因为从 Android 2.3 (API Level 9)开始,垃圾回收器会更倾向于回收持有软引用或弱引用的对象
LruCache的使用
首先来看LruCache的构造:new LruCache<String, Bitmap>
可以看出是由一个键值对组成其中键为String类型值为bitmap所以当我们使用的时候则可以将键作为图片的url值则传入bitmap
</pre><pre class="java" name="code"><span style="font-size:14px;font-family:NSimSun;line-height:2;color:#000000;">int MAXMEMONRY = (int) (Runtime.getRuntime()</span><span style="font-size:14px;font-family:NSimSun;line-height:2;color:#000000;"> .maxMemory() / 1024);</span>//获取手机的内存大小LruCache<String, Bitmap> mMemoryCache = new LruCache<String, Bitmap>(
MAXMEMONRY / 8) {//这里为手机内存大小/8
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// 重写此方法来衡量每张图片的大小,默认返回图片数量。
return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
}
@Override
protected void entryRemoved(boolean evicted, String key,
Bitmap oldValue, Bitmap newValue) { // evicted:true---为释放空间被删除;false---put或remove导致
Log.v("tag", "hard cache is full , push to soft cache");
}
};
清空缓存:public void clearCache(){ if(mMemoryCache!=null){ if(mMemoryCache.size()>0){ mMemoryCache.evictAll(); } mMemoryCache=null; }}添加图片到缓存:public void addbitmaptocache(String key,Bitmap bitmap){ if(mMemoryCache.get(key==null)){ mMemoryCache.put(key,bitmap); } }从缓存中取得图片:mMemoryCache.get(key);从缓存中移除对应key的缓存: public void removeImageCache(String key){ if(mMemoryCache!=null){ Bitmap bm=mMemoryCache.remove(key); if(bm!=null){ bm.recycle(); } } }
我们也可以利用trimToSize(int maxSize)用来清空cache
空间其中maxsize为预先设定的值也就是我们上面传入的
本文介绍了LruCache在Android中用于图片缓存的原因及实现方式。详细阐述了为何选择LruCache而非软引用或弱引用,并提供了具体的代码示例。
132

被折叠的 条评论
为什么被折叠?



