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

669 阅读6分钟

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

源码环境

版本: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 同步更新于本人的公众号,欢迎大家关注,一起交流学习~

在这里插入图片描述