这一节咱们将讲到Glide的内存缓存和磁盘缓存javascript
(网上流传的比较广的几篇文章都是直接从是一篇译文中拷贝过去的,那篇译文在许多地方都翻译错误了,其中很大的一个错误就是关于缓存一块的问题)java
Glide的缓存资源分为两种:面试
Glide默认是会在内存中缓存处理图(RESULT)的.缓存
能够经过调用skipMemoryCache(true)来设置跳过内存缓存网络
//跳过内存缓存
Glide.with(this).load(mUrl).skipMemoryCache(true).into(mIv);复制代码
调用skipMemoryCache(false)没有代码上的意义,由于Glide默认就是不跳过内存缓存的,可是显示调用这个方法,可让别人一目了然的知道你此次请求是会在内存中缓存的,因此仍是建议显示调用一下这个方法来代表你的内存缓存策略ide
Glide磁盘缓存策略分为四种,默认的是RESULT(默认值这一点网上不少文章都写错了,可是这一点很重要):工具
1.ALL:缓存原图(SOURCE)和处理图(RESULT)优化
2.NONE:什么都不缓存动画
3.SOURCE:只缓存原图(SOURCE)ui
4.RESULT:只缓存处理图(RESULT) ---默认值
和其余三级缓存同样,Glide的缓存读取顺序是 内存-->磁盘-->网络
须要注意的是Glide的内存缓存和磁盘缓存的配置相互没有直接影响,因此能够同时进行配置
例:
1.内存不缓存,磁盘缓存缓存全部图片
Glide.with(this).load(mUrl).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.ALL).into(mIv);复制代码
2.内存缓存处理图,磁盘缓存原图
Glide.with(this).load(mUrl).skipMemoryCache(false).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(mIv);复制代码
Glide的内存缓存其实涉及到比较多的计算,这里就介绍最重要的一个参数,就是内存缓存最大空间
内存缓存最大空间(maxSize)=每一个进程可用的最大内存 * 0.4
(低配手机的话是: 每一个进程可用的最大内存 * 0.33)
磁盘缓存大小: 250 1024 1024(250MB)
/** 250 MB of cache. */
int DEFAULT_DISK_CACHE_SIZE = 250 * 1024 * 1024;复制代码
磁盘缓存目录: 项目/cache/image_manager_disk_cache
String DEFAULT_DISK_CACHE_DIR = "image_manager_disk_cache";复制代码
清除全部内存缓存(须要在Ui线程操做)
Glide.get(this).clearMemory();复制代码
清除全部磁盘缓存(须要在子线程操做)
Glide.get(MainActivity.this).clearDiskCache();复制代码
注:在使用中的资源不会被清除
因为Glide可能会缓存一张图片的多个分辨率的图片,而且文件名是被哈希过的,因此并不能很好的删除单个资源的缓存,如下是官方文档中的描述
Because File names are hashed keys, there is no good way to simply delete all of the cached files on disk that
correspond to a particular url or file path. The problem would be simpler if you were only ever allowed to load
or cache the original image, but since Glide also caches thumbnails and provides various transformations, each
of which will result in a new File in the cache, tracking down and deleting every cached version of an image
is difficult.
In practice, the best way to invalidate a cache file is to change your identifier when the content changes
(url, uri, file path etc).复制代码