這一節咱們將講到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).複製代碼