我可能只是对LruCache
应该如何工作感到困惑,但它是否不允许从一个实例访问保存在另一个实例上的对象?当然不是这种情况,否则它会破坏拥有缓存的目的。
例:
class CacheInterface {
private val lruCache: LruCache<String, Bitmap>
init {
val maxMemory = (Runtime.getRuntime().maxMemory() / 1024).toInt()
// Use 1/8th of the available memory for this memory cache.
val cacheSize = maxMemory / 8
lruCache = object : LruCache<String, Bitmap>(cacheSize) {
override fun sizeOf(key: String, value: Bitmap): Int {
return value.byteCount / 1024
}
}
}
fun getBitmap(key: String): Bitmap? {
return lruCache.get(key)
}
fun storeBitmap(key: String, bitmap: Bitmap) {
lruCache.put(key, bitmap)
Utils.log(lruCache.get(key))
}
}
val bitmap = getBitmal()
val instance1 = CacheInterface()
instance1.storeBitmap("key1", bitmap)
log(instance1.getBitmap("key1")) //android.graphics.Bitmap@6854e91
log(CacheInterface().getBitmap("key1")) //null
据我了解,缓存一直被存储到用户删除(手动或卸载应用程序(或系统在超过允许空间时清除为止。我错过了什么?
LruCache
对象只是在内存中存储对对象的引用。一旦您丢失了对LruCache
的引用,LruCache
对象和该缓存中的所有对象都将被垃圾回收。磁盘上没有存储任何内容。
是的。我只是在这里分享我对什么感到困惑,以防有人也是。
最初是因为本指南(缓存位图(建议使用 LruCache
,我的印象是 LruCache 是访问应用程序缓存的接口,但就像@CommonsWare提到的它没有 I/O - 它只是一个使用 LRU 策略保存内存的实用程序类。要访问应用程序的缓存,您需要使用 Context.getCacheDir()
,这里解释得很好。就我而言,我最终使用了LruCache的单例,因为我已经有一个服务在运行,大多数时候该应用程序不会在每次关闭时都被杀死。
log(CacheInterface().getBitmap("key1")) //null
等于
val instance2 = CacheInterface()
log(instance2 .getBitmap("key1"))
实例 1 != 实例 2
更改为单例
object CacheInterface{
...
}
用
CacheInterface.storeBitmap("key1",bitmap)
CacheInterface.getBitmap("key1")