我正在开发一个显示大量图像的 Android 应用程序。我正在使用 Picasso 加载图像并使用其默认缓存策略。现在我想要的是修改缓存,假设如果用户今天看到了一张图片,它将在接下来的 7 天里在缓存中,每次用户访问该特定页面时,Picasso 从缓存中加载图片,7 天后图片将从缓存中清除并再次进行新的缓存。有人,请帮助我,我迷路了。
private void PicassoConfig() {
Picasso.Builder builder = new Picasso.Builder(this);
builder.downloader(new OkHttp3Downloader (this, Constants.MAX_DISK_CACHE_SIZE));
Picasso built = builder.build();
Picasso.setSingletonInstance(built);
}
然后
Picasso.get().load(cardList.get(i).
getImage()).noFade().priority(Picasso.Priority.HIGH).
placeholder(R.drawable.placehoder_image).
transform(new com.squareup.picasso.Transformation()
我希望图像在缓存中保留一周。
最佳答案
创建自定义 OkHttp interceptor并添加到 picasso 。
public Interceptor provideCacheInterceptor(final int maxDays) {
return new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
CacheControl cacheControl = new CacheControl.Builder()
.maxAge(maxDays, TimeUnit.DAYS)
.build();
return response.newBuilder()
.header(Constants.CACHE_CONTROL, cacheControl.toString())
.build();
}
};
}
现在,将其添加到 Gradle
compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.0.2'
现在将自定义 OkHttpClient
附加到 Picasso
。更多信息 here
okhttp3.OkHttpClient okHttp3Client = new okhttp3.OkHttpClient();
int MaxCacheDays = 7;
okHttp3Client.addNetworkInterceptor(provideCacheInterceptor(MaxCacheDays));
OkHttp3Downloader okHttp3Downloader = new OkHttp3Downloader(okHttp3Client);
Picasso picasso = new Picasso.Builder(context)
.downloader(new CustomOkHttp3Downloader(client))
.build();
关于android - 缓存图像一周,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57055984/