MemoryCacheUtils.java 用到了LruCache 很简单
我简单翻译下文档:
* A cache that holds strong references to a limited number of values. Each time
* a value is accessed, it is moved to the head of a queue. When a value is
* added to a full cache, the value at the end of that queue is evicted and may
* become eligible for garbage collection.
* Cache保存一个强引用来限制内容数量,每当Item被访问的时候,此Item就会移动到队列的头部。
* 当cache已满的时候加入新的item时,在队列尾部的item会被回收。
* <p>If your cached values hold resources that need to be explicitly released,
* override {@link #entryRemoved}.
* 如果你cache的某个值需要明确释放,重写entryRemoved()
* <p>By default, the cache size is measured in the number of entries. Override
* {@link #sizeOf} to size the cache in different units. For example, this cache
* is limited to 4MiB of bitmaps: 默认cache大小是测量的item的数量,重写sizeof计算不同item的
* 大小。
{@code
* int cacheSize = 4 * 1024 * 1024; // 4MiB
* LruCache<String, Bitmap> bitmapCache = new LruCache<String, Bitmap>(cacheSize) {
* protected int sizeOf(String key, Bitmap value) {
* return value.getByteCount();
* }
* }}
-------------------------------------------------------------------
<p>This class is thread-safe. Perform multiple cache operations atomically by
* synchronizing on the cache: <pre> {@code
* synchronized (cache) {
* if (cache.get(key) == null) {
* cache.put(key, value);
* }
* }}</pre>
* 他是线程安全的,自动地执行多个缓存操作并且加锁
-------------------------
<p>This class does not allow null to be used as a key or value. A return
* value of null from {@link #get}, {@link #put} or {@link #remove} is
* unambiguous: the key was not in the cache.
* 不允许key或者value为null
* 当get(),put(),remove()返回值为null时,key相应的项不在cache中
最重要的大概就是以上几点: 使用很简单
来看代码:
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
/**
* 内存缓存工具类
*
* @author Ace
* @date 2016-02-19
*/
public class MemoryCacheUtils {
// Android 2.3 (API Level
// 9)开始,垃圾回收器会更倾向于回收持有软引用或弱引用的对象,这让软引用和弱引用变得不再可靠,建议用LruCache,它是强引用
private LruCache<String, Bitmap> mCache;
public MemoryCacheUtils() {
int maxMemory = (int) Runtime.getRuntime().maxMemory();// 获取虚拟机分配的最大内存
// 16M
// LRU 最近最少使用, 通过控制内存不要超过最大值(由开发者指定), 来解决内存溢出,就像上面翻译的所说 如果cache满了会清理最近最少使用的缓存对象
mCache = new LruCache<String, Bitmap>(maxMemory / 8) {
@Override
protected int sizeOf(String key, Bitmap value) {
// 计算一个bitmap的大小
int size = value.getRowBytes() * value.getHeight();// 每一行的字节数乘以高度
return size;
}
};
}
public Bitmap getBitmapFromMemory(String url) {
return mCache.get(url);
}
public void setBitmapToMemory(String url, Bitmap bitmap) {
mCache.put(url, bitmap);
}
}










