参考Glide实现简易的图片缓存框架

Glide作为当下火爆的图片加载框架之一,相信大部分小伙伴们都有使用过的经历,当然我也是经常使用到。至于它的详细用法我们今天就不一一介绍了,相信在网上已经有很多优秀的文章可以参考,没有使用过的小伙伴们可以去自己搜索查看下。好的,我们直接进入正题,我们接下来来分析Glide的缓存机制,并参考Gilde的缓存机制手写一个自己的图片缓存框架。

口说无凭,通过查阅资料:https://muyangmin.github.io/glide-docs-cn/doc/caching.html#glide里的缓存Glide的缓存分为:

    1.活动资源(Active Resources) -当前页面正在显示的图片资源

    2. 内存缓存(Memory cache) -内存缓存

    3. 资源类型(Resource) -其实指的就是磁盘缓存

    4. 数据来源(Data) -网络、文件等数据源

一般图片加载的过程中(如果没有禁止使用缓存),应用会按照1,2,3,4的顺序来依次进行数据加载。需要注意一点是内存缓存还对应着一个Bitmap的复用池,当内存缓存需要舍弃图片时,如果图片是复用对象,是不会被立即回收掉的,而是会被暂时放在复用池当中。接下来我们就站在巨人的肩膀上,开始我们的构建我们自己的图片缓存框架,缓存结构包括:内存缓存,磁盘缓存,网络缓存。

在开始之前我们需要做些知识的储备:

1. Java弱引用 与 引用队列

2. LruCache的用法

3. DiskLruCache的用法

4. Bitmap复用机制

完成准备工作之后,接下来我们就进入正题。第一步根据需求,我们来定义一个接口,方便对方法进行管理


package com.example.learnglide;

import android.graphics.Bitmap;

/**

* 创建者:qinyafei

* 创建时间: 2019/6/20

* 描述: 图片缓存相关接口

* 版本信息:1.0.0

**/

public interface IImgaeCache {

/**

    * 初始化方法,因为要做磁盘缓存,所以我们在这里传入文件路径

    *

    * @param dir

    */

    void init(String dir);

    /**

    * 将图片放入内存缓存

    *

    * @param key

    * @param bitmap

    */

    void putSrc2MemoryCache(String key, Bitmap bitmap);

    /**

    * 从内存缓存中取得图片

    *

    * @param key

    * @return

    */

    Bitmap getBitmapFromMemory(String key);

    /**

    * 从复用池中获取图片数据

    *

    * @param width      所需图片宽度

    * @param height    所需图片高度

    * @param simpleSize 缩放大小

    * @return

    */

    Bitmap getSrcFromReuseableBimtmapPool(int width, int height, int simpleSize);

    /**

    * 将图片数据放入磁盘缓存

    * @param key

    * @param bitmap

    */

    void putBitmap2DiskCache(String key, Bitmap bitmap);

    /**

    * 从磁盘中获取图片,要考虑复用问题

    * @param reuseable

    * @return

    */

    Bitmap getSrcFromDiskCache(String key,Bitmap reuseable);

    /**

    * 清除缓存

    */

    void clearCache();

}

新建一个接口的实现类MyImageCache ,类采用单例模式。具体代码如下

package com.example.learnglide;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.util.LruCache;


import com.example.learnglide.disk.DiskLruCache;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * 创建者:qinyafei
 * 创建时间: 2019/6/20
 * 描述:
 * 版本信息:1.0.0
 **/
public class MyImageCache implements IImgaeCache {


    private static final int CACHE_SIZE = 10 * 1024 * 1024;

    private static MyImageCache instance;
    private Context context;
    private LruCache<String, Bitmap> memoryCache;// 内存缓存
    private DiskLruCache diskLruCache;// 磁盘缓存
    private BitmapFactory.Options options = new BitmapFactory.Options();


    public static Set<WeakReference<Bitmap>> reuseablePool;// 复用池
    ReferenceQueue referenceQueue; // 当弱引用被弃用时,会放到此队列中
    Thread gcThread;// 手动回收线程
    boolean shutDown;

    private MyImageCache(Context context) {
        this.context = context.getApplicationContext();// 为避免内存泄漏
    }

    public static MyImageCache getInstance(Context context) {

        if (null == instance) {
            synchronized (MyImageCache.class) {
                if (null == instance) {
                    instance = new MyImageCache(context);
                }
            }
        }

        return instance;
    }

    @Override
    public void init(String dir) {

        // 构建一个线程安全的复用池,考虑到图片加载多在子线程中进行
        reuseablePool = Collections.synchronizedSet(new HashSet<WeakReference<Bitmap>>());
        intiReferenceQueue();
        memoryCache = new LruCache<String, Bitmap>(CACHE_SIZE) {
            /**
             * @return 图片占用内存大小
             */
            @Override
            protected int sizeOf(String key, Bitmap value) {
                //19之前必需同等大小,才能复用  inSampleSize=1
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
                    return value.getAllocationByteCount();
                }
                return value.getByteCount();
            }

            @Override
            protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {
                if (oldValue.isMutable()) {
                    // 如果是可复用的,不直接回收,而是暂时放于复用池中
                    reuseablePool.add(new WeakReference<Bitmap>(oldValue, referenceQueue));
                } else {
                    oldValue.recycle();
                }
            }
        };
        try {
            diskLruCache = DiskLruCache.open(new File(dir), BuildConfig.VERSION_CODE, 1, 10 * 1024 * 1024);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 初始化引用队列 && 回收线程
     */
    private void intiReferenceQueue() {
        if (null == referenceQueue) {
            referenceQueue = new ReferenceQueue<Bitmap>();
            //开启一个回收线程,在检测到有可回收对象时,
            // 手动回收,避免了GC的等待时间,让内存处理更高效
            gcThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (!shutDown) {
                        try {
                            Reference<Bitmap> reference = referenceQueue.remove();
                            Bitmap bitmap = reference.get();
                            if (null != bitmap && !bitmap.isRecycled()) {
                                bitmap.recycle();
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            gcThread.start();
        }
    }

    @Override
    public void putSrc2MemoryCache(String key, Bitmap bitmap) {
        memoryCache.put(key, bitmap);
    }

    @Override
    public Bitmap getBitmapFromMemory(String key) {
        return memoryCache.get(key);
    }

    @Override
    public Bitmap getSrcFromReuseableBimtmapPool(int width, int height, int simpleSize) {

        // api 11 之前是不存在Bitmap服用的
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            Bitmap reuseable = null;
            Iterator<WeakReference<Bitmap>> iterator = reuseablePool.iterator();
            while (iterator.hasNext()) {
                Bitmap bitmap = iterator.next().get();
                if (null != bitmap) {
                    if (isBitmapCanResueable(bitmap, width, height, simpleSize)) {
                        reuseable = bitmap;
                        iterator.remove();
                        break;
                    } else {
                        iterator.remove();
                    }
                }
            }
            return reuseable;
        }
        return null;
    }

    @Override
    public void putBitmap2DiskCache(String key, Bitmap bitmap) {
        DiskLruCache.Snapshot snapshot = null;
        OutputStream os = null;
        try {
            snapshot = diskLruCache.get(key);
            //如果缓存中已经有这个文件  不理他
            if (null == snapshot) {
                //如果没有这个文件,就生成这个文件
                DiskLruCache.Editor editor = diskLruCache.edit(key);
                if (null != editor) {
                    os = editor.newOutputStream(0);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 50, os);
                    editor.commit();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != snapshot) {
                snapshot.close();
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public Bitmap getSrcFromDiskCache(String key, Bitmap reuseable) {
        DiskLruCache.Snapshot snapshot = null;
        Bitmap bitmap = null;
        try {
            snapshot = diskLruCache.get(key);
            if (null == snapshot) {
                return null;
            }
            InputStream is = snapshot.getInputStream(0);
            options.inMutable = true;
            options.inBitmap = reuseable;
            bitmap = BitmapFactory.decodeStream(is, null, options);
            if (null != bitmap) {
                memoryCache.put(key, bitmap);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != snapshot) {
                snapshot.close();
            }
        }
        return bitmap;
    }

    @Override
    public void clearCache() {
        memoryCache.evictAll();
    }


    /**
     * 检查图片是否可以进行复用
     *
     * @param bitmap
     * @param w
     * @param h
     * @param inSampleSize
     * @return
     */
    private boolean isBitmapCanResueable(Bitmap bitmap, int w, int h, int inSampleSize) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            return bitmap.getWidth() == w && bitmap.getHeight() == h && inSampleSize == 1;
        }
        if (inSampleSize >= 1) {
            w /= inSampleSize;
            h /= inSampleSize;
        }
        int byteCount = w * h * getPixelsCount(bitmap.getConfig());
        return byteCount <= bitmap.getAllocationByteCount();
    }

    /**
     * 获取每个像素的字节数目
     *
     * @param config
     * @return
     */
    private int getPixelsCount(Bitmap.Config config) {
        if (config == Bitmap.Config.ARGB_8888) {
            return 4;
        }
        return 2;
    }
}

至此有关缓存的代码就书写完成了,接下来定义一个类来使用这些缓存,代码如下:

public class ImageLoadUtil {


    /**
     * 加载图片
     * @param context
     * @param key
     * @param width
     * @param height
     * @param simpleSize 缩放比例
     * @return
     */
    public static Bitmap loadImage(Context context, String key, int width, int height, int simpleSize) {
        Bitmap bitmap = MyImageCache.getInstance(context).getBitmapFromMemory(key);// 从内存中找
        if (null == bitmap) {
            Bitmap reuseable = MyImageCache.getInstance(context).getSrcFromReuseableBimtmapPool(width, height, simpleSize);
            bitmap = MyImageCache.getInstance(context).getSrcFromDiskCache(key, reuseable);
            if (null == bitmap) {  //如果磁盘中也没缓存,就从网络下载,这里使用本地图片模拟网络图片
                Log.e("Img_Test", "从网络加载: ");
                bitmap = resizeBitmap(context, R.drawable.test, 80, 80, false, reuseable);
                MyImageCache.getInstance(context).putBitmap2DiskCache(key, bitmap);
                MyImageCache.getInstance(context).putSrc2MemoryCache(key, bitmap);
            }else {
                Log.e("Img_Test", "从磁盘加载: ");
            }
        }else {
            Log.e("Img_Test", "从内存加载: ");
        }
        return bitmap;
    }
}


大功告成,如有什么错误和不足的地方,还望各位指正。最后附上Demo地址:GitHub - qinyafeiii/LearnGlide: 参照Glide,手写图片缓存框架

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容