我正在使用 picasso 为我的应用加载图像。没有一个特别大,但它只缓存到内存,所以我在图像重页上遇到内存不足错误。我需要在 picasso 或模拟器中手动设置什么来启用磁盘缓存吗?
问问题
2933 次
2 回答
2
您是否在 Picasso 中提供了自定义下载器?您应该确保以下几点:
- 您是否有权写入指定的缓存文件夹?
- 您的缓存大小限制是否足以容纳毕加索正在下载的图像?
这是将图像写入 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 从不缓存的可能性。对于测试,我建议:
- 启用毕加索的
setDebugging(true)
;从磁盘重新加载图像时,您应该会看到一个黄色标记。 - 在测试缓存时杀死你的应用程序;绿色标记表示它来自内存缓存。
- 从您确定服务器未发送 cache-expiry/no-pragma 标头的静态位置下载图像。
于 2013-10-30T11:57:23.893 回答
0
从:
//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);
于 2014-04-12T16:58:40.717 回答