作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 coil(version 2.1.0)从 URL 加载图像。当有网络连接时,图像加载正常。但是,当没有网络连接时,图像不会像我预期的那样从缓存中提取出来。这是我的一段代码。
class App : Application(), ImageLoaderFactory {
override fun newImageLoader(): ImageLoader {
return ImageLoader.Builder(this)
.memoryCache {
MemoryCache.Builder(this)
.maxSizePercent(0.25)
.build()
}
.diskCache {
DiskCache.Builder()
.directory(cacheDir.resolve("image_cache"))
.maxSizeBytes(5 * 1024 * 1024)
.build()
}
.build()
}
}
在撰写中:
val context = LocalContext.current
val placeholderImage = R.drawable.ic_placeholder
val imageRequest = ImageRequest.Builder(context)
.data(imageUrl)
.memoryCacheKey(imageUrl)
.diskCacheKey(imageUrl)
.placeholder(placeholderImage)
.error(placeholderImage)
.fallback(placeholderImage)
.diskCachePolicy(CachePolicy.ENABLED)
.memoryCachePolicy(CachePolicy.ENABLED)
.transformations(CircleCropTransformation())
.build()
AsyncImage(
model = imageRequest,
modifier = Modifier.size(64.dp),
contentDescription = null,
imageLoader = context.imageLoader
)
当设备处于离线状态时,它只会加载占位符图像,而不是像预期的那样从缓存中加载图像。我在这里缺少什么?
最佳答案
coil 将根据 http header 中的 Cache-Control
字段来决定是否需要磁盘缓存。
这里是coil 2.0.0的更新日志
- New: Introduce a public
DiskCache
API.
- Use
ImageLoader.Builder.diskCache
andDiskCache.Builder
to configure the disk cache.- You should not use OkHttp's
Cache
with Coil 2.0. See here for moreinfo.Cache-Control
and other cache headers are still supported - exceptVary
headers, as the cache only checks that the URLs match.Additionally, only responses with a response code in the range[200..300) are cached.- Existing disk caches will be cleared when upgrading to 2.0.
如果需要强制缓存,参见https://coil-kt.github.io/coil/recipes/#headers .而且我认为最好使用 addHeader
来避免丢弃其他 http header 字段。
关于android - 线圈图像缓存不适用于 Jetpack Compose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72981927/
我是一名优秀的程序员,十分优秀!