Android UIL图片加载缓存源码分析-硬盘缓存

上面一篇文章《Android UIL图片加载缓存源码分析-内存缓存》我们已经分析了Android著名的图片加载库UIL的内存缓存模型,本篇文章我们接着分析另外一种缓存方式-磁盘缓存,磁盘缓存说到底就是将图片缓存到本地SD卡中,我们通过UIL的磁盘缓存来分析一下。

image

源码环境

版本:V1.9.5
GitHub链接地址:https://github.com/nostra13/Android-Universal-Image-Loader

DiskCache.java (接口)

/**
 * Interface for disk cache
 *
 * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
 * @since 1.9.2
 */
public interface DiskCache {
    /**
     * Returns root directory of disk cache
     * 返回磁盘缓存的根目录
     * @return Root directory of disk cache
     */
    File getDirectory();
    /**
     * Returns file of cached image
     * 通过imageUri返回文件类型的bitmap
     * @param imageUri Original image URI
     * @return File of cached image or <b>null</b> if image wasn't cached
     */
    File get(String imageUri);
    /**
     * 缓存图片
     * Saves image stream in disk cache.
     * Incoming image stream shouldn't be closed in this method.
     *
     * @param imageUri    Original image URI
     * @param imageStream Input stream of image (shouldn't be closed in this method)
     * @param listener    Listener for saving progress, can be ignored if you don't use
     *                    {@linkplain com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener
     *                    progress listener} in ImageLoader calls
     * @return <b>true</b> - if image was saved successfully; <b>false</b> - if image wasn't saved in disk cache.
     * @throws java.io.IOException
     */
    boolean save(String imageUri, InputStream imageStream, IoUtils.CopyListener listener) throws IOException;
    /**
     * Saves image bitmap in disk cache.
     *
     * @param imageUri Original image URI
     * @param bitmap   Image bitmap
     * @return <b>true</b> - if bitmap was saved successfully; <b>false</b> - if bitmap wasn't saved in disk cache.
     * @throws IOException
     */
    boolean save(String imageUri, Bitmap bitmap) throws IOException;
    /**
     * 移除图片
     * Removes image file associated with incoming URI
     *
     * @param imageUri Image URI
     * @return <b>true</b> - if image file is deleted successfully; <b>false</b> - if image file doesn't exist for
     * incoming URI or image file can't be deleted.
     */
    boolean remove(String imageUri);
    /** Closes disk cache, releases resources. */
    void close();
    /** 
    * 清空磁盘中的缓存
    * Clears disk cache. */
    void clear();
}

同内存缓存图片一样,磁盘缓存也设计了一个基础的接口,各种不同方式的磁盘缓存方式实现该接口来实现不同的缓存策略。

我们来分析一下UIL默认的磁盘缓存策略,UnlimitedDiskCache,该缓存方式是UIL的默认缓存方式,我们分析一下源码可以发现:

UnlimitedDiskCache.java (类,默认缓存方式)

/**
 * Default implementation of {@linkplain com.nostra13.universalimageloader.cache.disc.DiskCache disk cache}.
 * Cache size is unlimited.
 *
 * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
 * @since 1.0.0
 */
public class UnlimitedDiskCache extends BaseDiskCache {
    /** @param cacheDir Directory for file caching */
    public UnlimitedDiskCache(File cacheDir) {
        super(cacheDir);
    }
    /**
     * @param cacheDir        Directory for file caching
     * @param reserveCacheDir null-ok; Reserve directory for file caching. It's used when the primary directory isn't available.
     */
    public UnlimitedDiskCache(File cacheDir, File reserveCacheDir) {
        super(cacheDir, reserveCacheDir);
    }
    /**
     * @param cacheDir          Directory for file caching
     * @param reserveCacheDir   null-ok; Reserve directory for file caching. It's used when the primary directory isn't available.
     * @param fileNameGenerator {@linkplain com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator
     *                          Name generator} for cached files
     */
    public UnlimitedDiskCache(File cacheDir, File reserveCacheDir, FileNameGenerator fileNameGenerator) {
        super(cacheDir, reserveCacheDir, fileNameGenerator);
    }
}

我们发现该缓存方式比较简单,只有几个构造函数,我们发现它是集成BaseDiskCache的,所以我们接着分析BaseDiskCache的源代码。

BaseDiskCache.java (类)

/**
 * 基础的磁盘缓存,抽象类
 * Base disk cache.
 *
 * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
 * @see FileNameGenerator
 * @since 1.0.0
 */
public abstract class BaseDiskCache implements DiskCache {
    /** {@value  默认的缓存大小32Kb*/
    public static final int DEFAULT_BUFFER_SIZE = 32 * 1024; // 32 Kb
    /** {@value 默认的png图片格式*/
    public static final Bitmap.CompressFormat DEFAULT_COMPRESS_FORMAT = Bitmap.CompressFormat.PNG;
    
    /** {@value 压缩质量100,不压缩*/
    public static final int DEFAULT_COMPRESS_QUALITY = 100;
    private static final String ERROR_ARG_NULL = " argument must be not null";
    //图片临时后缀tmp
    private static final String TEMP_IMAGE_POSTFIX = ".tmp";
    
    //文件缓存路径
    protected final File cacheDir;
    //备用的文件缓存目录,可以为null。它只有当cacheDir不能用的时候才有用。
    protected final File reserveCacheDir;
    
    //文件名生成器。为缓存的文件生成文件名。
    protected final FileNameGenerator fileNameGenerator;
    protected int bufferSize = DEFAULT_BUFFER_SIZE;
    protected Bitmap.CompressFormat compressFormat = DEFAULT_COMPRESS_FORMAT;
    protected int compressQuality = DEFAULT_COMPRESS_QUALITY;
    //....
}

接下来我们看下该类的构造器

 
/** @param cacheDir Directory for file caching */
public BaseDiskCache(File cacheDir) {
    this(cacheDir, null);
}
/**
 * 只有当设置的文件路径不能用时,我们才使用备份的文件目录
 * @param cacheDir        Directory for file caching
 * @param reserveCacheDir null-ok; Reserve directory for file caching. It's used when the primary directory isn't available.
 */
public BaseDiskCache(File cacheDir, File reserveCacheDir) {
    //使用默认的文件名生成器
    this(cacheDir, reserveCacheDir, DefaultConfigurationFactory.createFileNameGenerator());
}
/**
 * @param cacheDir          Directory for file caching
 * @param reserveCacheDir   null-ok; Reserve directory for file caching. It's used when the primary directory isn't available.
 * @param fileNameGenerator {@linkplain com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator
 *                          Name generator} for cached files
 */
public BaseDiskCache(File cacheDir, File reserveCacheDir, FileNameGenerator fileNameGenerator) {
    if (cacheDir == null) {
        throw new IllegalArgumentException("cacheDir" + ERROR_ARG_NULL);
    }
    if (fileNameGenerator == null) {
        throw new IllegalArgumentException("fileNameGenerator" + ERROR_ARG_NULL);
    }
    this.cacheDir = cacheDir;
    this.reserveCacheDir = reserveCacheDir;
    this.fileNameGenerator = fileNameGenerator;
}

在第二个构造函数中,我们看到了生成了默认的文件名称生成器,我们来具体看看里面如何运作的。

//DefaultConfigurationFactory.java
/** Creates {@linkplain HashCodeFileNameGenerator default implementation} of FileNameGenerator */
    public static FileNameGenerator createFileNameGenerator() {
        return new HashCodeFileNameGenerator();
    }
//HashCodeFileNameGenerator.java
/**
 * Names image file as image URI {@linkplain String#hashCode() hashcode}
 *
 * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
 * @since 1.3.1
 */
public class HashCodeFileNameGenerator implements FileNameGenerator {
    @Override
    public String generate(String imageUri) {
        return String.valueOf(imageUri.hashCode());
    }
}

看到没?非常简单,就是一个imageURI的hash码,真的是你意想不到的简单,就是运用String.hashCode()进行文件名的生成。我们看完了图片磁盘缓存的命名策略后继续分析下面的代码:

@Override
public boolean save(String imageUri, InputStream imageStream, IoUtils.CopyListener listener) throws IOException {
    File imageFile = getFile(imageUri);
    File tmpFile = new File(imageFile.getAbsolutePath() + TEMP_IMAGE_POSTFIX);
    boolean loaded = false;
    try {
        OutputStream os = new BufferedOutputStream(new FileOutputStream(tmpFile), bufferSize);
        try {
            loaded = IoUtils.copyStream(imageStream, os, listener, bufferSize);
        } finally {
            IoUtils.closeSilently(os);
        }
    } finally {
        if (loaded && !tmpFile.renameTo(imageFile)) {
            loaded = false;
        }
        if (!loaded) {
            tmpFile.delete();
        }
    }
    return loaded;
}

其中涉及到一个方法getFile,我们具体看下什么内容:

/** 它主要用于生成一个指向缓存目录中的文件
* Returns file object (not null) for incoming image URI. File object can reference to non-existing file. */
    protected File getFile(String imageUri) {
        
        //文件名生成器生成文件名
        String fileName = fileNameGenerator.generate(imageUri);
        File dir = cacheDir;
        if (!cacheDir.exists() && !cacheDir.mkdirs()) {
            if (reserveCacheDir != null && (reserveCacheDir.exists() || reserveCacheDir.mkdirs())) {
                dir = reserveCacheDir;
            }
        }
        return new File(dir, fileName);
    }

注意save方法中第3行的tmpFile,它是用来写入bitmap的临时文件(见第8行),然后就把这个文件给删除了。在getFile方法中,让我们来分析一下这个在之前碰过的函数。 第2行就是利用fileNameGenerator生成一个唯一的文件名。第3~8行是指定缓存目录,这时候你就可以清楚地看到cacheDir和reserveCacheDir之间的关系了,当cacheDir不可用的时候,就是用reserveCachedir作为缓存目录了。最后返回一个指向文件的对象,但是要注意当File类型的对象指向的文件不存在时,file会为null,而不是报错。

磁盘缓存总结

现在,我们已经分析了UIL的缓存机制。其实从UIL的缓存机制的实现并不是很复杂,虽然有各种缓存机制,但是简单地说:内存缓存其实就是利用Map接口的对象在内存中进行缓存,可能有不同的存储机制。磁盘缓存其实就是将文件写入磁盘。

  1. FileCountLimitedDiscCache(可以设定缓存图片的个数,当超过设定值,删除掉最先加入到硬盘的文件,最新版本已删除)
  2. LimitedAgeDiscCache(设定文件存活的最长时间,当超过这个值,就删除该文件)
  3. TotalSizeLimitedDiscCache(设定缓存bitmap的最大值,当超过这个值,删除最先加入到硬盘的文件,最新版本已删除)
  4. UnlimitedDiscCache(这个缓存类没有任何的限制)
  5. LruDiskCache (最近最少使用磁盘缓存,也使用了内存缓存类似的相关策略)

在UIL中有着比较完整的存储策略,根据预先指定的空间大小,使用频率(生命周期),文件个数的约束条件,都有着对应的实现策略。最基础的接口DiscCacheAware和抽象类BaseDiscCache

关于作者

专注于 Android 开发多年,喜欢写 blog 记录总结学习经验,blog 同步更新于本人的公众号,欢迎大家关注,一起交流学习~

在这里插入图片描述
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,524评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,869评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,813评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,210评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,085评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,117评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,533评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,219评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,487评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,582评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,362评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,218评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,589评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,899评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,176评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,503评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,707评论 2 335

推荐阅读更多精彩内容