CacheDiskUtils
之前寫過一篇 你想要的 CacheUtils,簡單介紹了下其可以完美替代 ASimpleCache,而且修復(fù)了其中少許 BUG 并做了相應(yīng)優(yōu)化,相關(guān) API 如下所示:
緩存相關(guān) -> CacheUtils.java
getInstance : 獲取緩存實(shí)例
Instance.put : 緩存中寫入數(shù)據(jù)
Instance.getBytes : 緩存中讀取字節(jié)數(shù)組
Instance.getString : 緩存中讀取 String
Instance.getJSONObject : 緩存中讀取 JSONObject
Instance.getJSONArray : 緩存中讀取 JSONArray
Instance.getBitmap : 緩存中讀取 Bitmap
Instance.getDrawable : 緩存中讀取 Drawable
Instance.getParcelable : 緩存中讀取 Parcelable
Instance.getSerializable: 緩存中讀取 Serializable
Instance.getCacheSize : 獲取緩存大小
Instance.getCacheCount : 獲取緩存?zhèn)€數(shù)
Instance.remove : 根據(jù)鍵值移除緩存
Instance.clear : 清除所有緩存
其也就是所謂的硬盤緩存,在 AndroidUtilCode 1.17.0 版本,該 CacheUtils 已被我標(biāo)記廢棄,可替換為 CacheDiskUtils,下一個大版本1.18.x 可能就會移除 CacheUtils。
CacheMemoryUtils
講了磁盤緩存另一個就是內(nèi)存緩存,內(nèi)存緩存工具類 CacheMemoryUtils 原理是利用 LruCache 來實(shí)現(xiàn)的(LRU 是Least Recently Used的縮寫,即最近最少使用),其 API 如下所示:
內(nèi)存緩存相關(guān) -> CacheMemoryUtils.java -> Test
getInstance : 獲取緩存實(shí)例
Instance.put : 緩存中寫入數(shù)據(jù)
Instance.get : 緩存中讀取字節(jié)數(shù)組
Instance.getCacheCount: 獲取緩存?zhèn)€數(shù)
Instance.remove : 根據(jù)鍵值移除緩存
Instance.clear : 清除所有緩存
CacheDoubleUtils
結(jié)合硬盤緩存工具類 CacheDiskUtils 和內(nèi)存緩存工具類 CacheMemoryUtils,那么我們的二級緩存工具類 CacheDoubleUtils 便誕生了,其 API 如下所示:
二級緩存相關(guān) -> CacheDoubleUtils.java -> Test
getInstance : 獲取緩存實(shí)例
Instance.put : 緩存中寫入數(shù)據(jù)
Instance.getBytes : 緩存中讀取字節(jié)數(shù)組
Instance.getString : 緩存中讀取 String
Instance.getJSONObject : 緩存中讀取 JSONObject
Instance.getJSONArray : 緩存中讀取 JSONArray
Instance.getBitmap : 緩存中讀取 Bitmap
Instance.getDrawable : 緩存中讀取 Drawable
Instance.getParcelable : 緩存中讀取 Parcelable
Instance.getSerializable : 緩存中讀取 Serializable
Instance.getCacheDiskSize : 獲取磁盤緩存大小
Instance.getCacheDiskCount : 獲取磁盤緩存?zhèn)€數(shù)
Instance.getCacheMemoryCount: 獲取內(nèi)存緩存?zhèn)€數(shù)
Instance.remove : 根據(jù)鍵值移除緩存
Instance.clear : 清除所有緩存
借助以上三個緩存工具類,那么 Android 端的緩存實(shí)現(xiàn)便再也不是什么難題了,例如你想要實(shí)現(xiàn) RxCache,那么借助 RxJava 的 compose 操作符和我的工具類,把數(shù)據(jù)放入緩存不就輕而易舉地實(shí)現(xiàn)了么,更多風(fēng)騷的姿勢可待你解鎖。