我找不到这个问题的更新答案。我正在使用 Volley 向 Web API 发送请求。它返回 JSON。我正在使用如下所示的缓存功能,但我想确保列表视图经常刷新(现在假设为 30 分钟)。如何使该给定 URL 的缓存无效,以便我的应用程序自动处理该 URL(无需刷新按钮)。这question https://stackoverflow.com/questions/17230431/google-volley-when-to-use-cache-remove-and-cache-invalidate有助于指出无效和删除之间的区别。
MainActivity.java
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONArray(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else
{
// making fresh volley request and getting json
JsonArrayRequest getRequest = new JsonArrayRequest(URL_FEED,
new Response.Listener<JSONArray>()
{
@Override public void onResponse(JSONArray response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
Log.d("Response", response.toString());
}
},......ErrorListener
要刷新列表视图,您可以使用 volley服务器日期获取最初收到响应的日期
AppController.getInstance().getRequestQueue().getCache().get(url).serverDate
这个返回日期时间很长。
并在您的代码中使用分钟差异函数作为
public static long getMinutesDifference(long timeStart,long timeStop){
long diff = timeStop - timeStart;
long diffMinutes = diff / (60 * 1000);
return diffMinutes;
}
并在代码中调用此函数
Calendar calendar = Calendar.getInstance();
long serverDate = AppController.getInstance().getRequestQueue().getCache().get(url).serverDate;
if(getMinutesDifference(serverDate, calendar.getTimeInMillis()) >=30){
AppController.getInstance().getRequestQueue().getCache().invalidate(URL_FEED, true);
}
如果之前的 url 响应 >=30 分钟,它将使缓存失效。
This (无效)允许继续使用此数据,直到进行新的调用并且缓存的响应被新响应覆盖。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)