如何更改Volley中默认磁盘缓存行为?

5

我正在使用的图像获取服务和许多类似网站一样,没有缓存控制头来指示图像应该被缓存多长时间。 Volley默认使用http缓存控制头来决定在磁盘上缓存图像的时间。我该如何覆盖此默认行为并将这些图像保留一段时间?

谢谢。

1个回答

11

我需要更改默认缓存策略为“全部缓存”,而不考虑HTTP标头。

您想为一段时间进行缓存。由于代码中有许多与网络响应相关的地方,因此有几种方法可以实现这一点。我建议对HttpHeaderParser进行编辑(位于第39行的parseCacheHeaders方法):

Cache.Entry entry = new Cache.Entry();
entry.data = response.data;
entry.etag = serverEtag;
entry.softTtl = softExpire;
entry.ttl = now; // **Edited**
entry.serverDate = serverDate;
entry.responseHeaders = headers;

另外一个与Cache.Entry类相关的:

/** True if the entry is expired. */
public boolean isExpired() {
    return this.ttl + GLOBAL_TTL < System.currentTimeMillis();
}

/** True if a refresh is needed from the original data source. */
public boolean refreshNeeded() {
    return this.softTtl + GLOBAL_TTL < System.currentTimeMillis();
}

GLOBAL_TTL是一个常量,代表你希望每个图像在缓存中保存的时间。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接