内存缓存图片及原理

垃圾回收器与引用

垃圾回收器只会回收没有引用的对象,不及时回收
默认为强引用,垃圾回收器不会回收
软引用,垃圾回收器会考虑回收 SoftReference类
弱引用,垃圾回收器最会考虑回收 WeakReference类
虚引用,垃圾回收器优先考虑回收 PhantomReference类

因为从 Android 2.3 (API Level 9)开始,垃圾回收器会更倾向于回收持有软引用或弱引用的对象,这让软引用和弱引用变得不再可靠。Google建议使用LruCache,注释代码使用软引用

 public class MemoryCacheUtils {

    // private HashMap<String, Bitmap> mMemoryCache = new HashMap<String,
    // Bitmap>();
    // private HashMap<String, SoftReference<Bitmap>> mMemoryCache = new
    // HashMap<String, SoftReference<Bitmap>>();

    private LruCache<String, Bitmap> mMemoryCache;

    public MemoryCacheUtils() {
        // LruCache 可以将最近最少使用的对象回收掉, 从而保证内存不会超出范围
        // Lru: least recentlly used 最近最少使用算法
        long maxMemory = Runtime.getRuntime().maxMemory();// 获取分配给app的内存大小
        System.out.println("maxMemory:" + maxMemory);

        mMemoryCache = new LruCache<String, Bitmap>((int) (maxMemory / 8)) {

            // 返回每个对象的大小
            @Override
            protected int sizeOf(String key, Bitmap value) {
                // int byteCount = value.getByteCount();
                int byteCount = value.getRowBytes() * value.getHeight();// 计算图片大小:每行字节数*高度
                return byteCount;
            }
        };
    }

    /**
     * 写缓存
     */
    public void setMemoryCache(String url, Bitmap bitmap) {
        // mMemoryCache.put(url, bitmap);
        // SoftReference<Bitmap> soft = new SoftReference<Bitmap>(bitmap);//
        // 使用软引用将bitmap包装起来
        // mMemoryCache.put(url, soft);
        mMemoryCache.put(url, bitmap);
    }

    /**
     * 读缓存
     */
    public Bitmap getMemoryCache(String url) {
        // SoftReference<Bitmap> softReference = mMemoryCache.get(url);
        //
        // if (softReference != null) {
        // Bitmap bitmap = softReference.get();
        // return bitmap;
        // }

        return mMemoryCache.get(url);
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值