【问题标题】:Picasso never caches to disk on emulatorPicasso 从不缓存到模拟器上的磁盘
【发布时间】:2013-09-07 07:57:57
【问题描述】:

我正在使用 picasso 为我的应用加载图像。没有一个特别大,但它只缓存到内存,所以我在图像重页上遇到内存不足错误。我需要在 picasso 或模拟器中手动设置什么来启用磁盘缓存吗?

【问题讨论】:

  • 虽然描述中提到了磁盘缓存,但我在 JavaDocs 中没有看到任何引用它的内容。
  • 你怎么知道它只缓存在内存中?加载几张图片后,您是否尝试过飞行模式? (重新启动进程)。还要在您的实例中调用 debug(true)。另外,它使用的是什么下载器? OkHttpDownloader 还是 UrlConnectionDownloader?可能是磁盘缓存无法安装。
  • 我认为它只是在内存中缓存,因为我设置了调试(true)并且只看到红色和绿色标签。但是,在按照您的建议加载一些图像后,我尝试将模拟器设置为飞行模式并关闭计算机上的 wifi,当它们在屏幕外重新加载时,它们会重新出现红色标签。也许它正在缓存到内存,只是没有显示正确的调试指标?不确定是什么下载器,我的目标是 sdk 14+,所以我假设 OkHttpDownloader?
  • 这可能是模拟器的问题或缺少缓存的标头。您是否尝试过其他网址而不是您自己的网址?也许是随毕加索样品一起提供的。

标签: android caching image-loading picasso


【解决方案1】:

您是否在 Picasso 中提供了自定义下载器?您应该确保以下几点:

  1. 您是否有权写入指定的缓存文件夹?
  2. 您的缓存大小限制是否足以容纳毕加索正在下载的图像?

这是一个将图像写入 SD 卡上的缓存目录的示例实现:

// Obtain the external cache directory
File cacheDir = context.getExternalCacheDir();
if (cacheDir == null) {
    // Fall back to using the internal cache directory
    cacheDir = context().getCacheDir();
}
// Create a response cache using the cache directory and size restriction
HttpResponseCache responseCache = new HttpResponseCache(
        cacheDir,
        10 * 1024 * 1024);
// Prepare OkHttp
httpClient = new OkHttpClient();
httpClient.setResponseCache(responseCache);
// Build Picasso with this custom Downloader
new Picasso.Builder(getContext())
         .downloader(new OkHttpDownloader(httpClient))
         .build();

我没有对此进行测试,但也存在服务器返回 HTTP 标头指示 OkHttp 从不缓存的可能性。对于测试,我建议:

  1. 启用毕加索的setDebugging(true);从磁盘重新加载图像时,您应该会看到一个黄色标记。
  2. 测试缓存时杀死你的应用程序;绿色标记表示它来自内存缓存。
  3. 从您确定服务器未发送 cache-expiry/no-pragma 标头的静态位置下载图像。

【讨论】:

  • 我有这段代码,图片在 Picasso 缓存目录中,但日志显示:发送进度 READING_FROM_CACHE 缓存内容不可用或过期或禁用任何想法?提前致谢。
【解决方案2】:

发件人:

How to implement my own disk cache with picasso library - Android?

//this code from https://developer.android.com/reference/android/net/http/HttpResponseCache.html
try {
       File httpCacheDir = new File(context.getCacheDir(), "http");
       long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
       HttpResponseCache.install(httpCacheDir, httpCacheSize);
}catch (IOException e) {
       Log.i(TAG, "HTTP response cache installation failed:" + e);
}

并启用调试以检查缓存是否正常工作 Picasso.with(getContext()).setDebugging(true);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 2015-06-13
    • 2016-06-25
    • 2015-05-16
    • 2016-03-16
    • 2014-07-21
    • 2018-08-22
    相关资源
    最近更新 更多