如何自动清除Volley缓存?

13

我希望每30分钟清除一次请求队列。

那么,自动清除volley缓存的最佳方法是什么?

通过扩展volley缓存类覆盖方法?

还是构建一个定时器,在需要时清除缓存?


https://dev59.com/EmQm5IYBdhLWcg3w6SlR - IntelliJ Amiya
那么,你认为我只需要使数据失效吗?我的问题是如何自动使数据失效或清除,而不需要任何刷新按钮。 - JohnnyBeGoody
1
我发布了我的解决方案,也许能帮到别人。我使用一个继承TimeTask的类,并在run方法中清除volley缓存。 - JohnnyBeGoody
3个回答

23

Google Volley提供了2种从缓存中清除项目的方式:

AppController.getInstance().getRequestQueue().getCache().remove(key);

AppController.getInstance().getRequestQueue().getCache().invalidate(key, fullExpire);

移除(Remove)表示您正在删除实际缓存的数据。

使无效(Invalidate) 表示您只是将数据标记为无效。因此,Volley会与服务器检查数据是否仍然有效。 完全过期(full expire)确定在Volley验证它与服务器之前是否使用数据。

要每隔30分钟清除缓存,请使用以下代码:

您可以使用Volley的 serverDate获取响应最初接收的日期。

AppController.getInstance().getRequestQueue().getCache().get(url).serverDate

所以在你的代码中使用 getMinutesDifference 函数,如下:

  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, true);
}

如果先前的 URL 响应时间大于等于 30 分钟,则会使缓存无效。


1
你好 Giru Bhai, AppController.getInstance().getRequestQueue().getCache().remove(key);在上面的代码中,"key" 是什么?我遇到了 Volley 缓存问题... - patel135

1

简单的方法是重写onRequestFinished方法并清除缓存。或者您可以在30分钟后在计时器内运行。

final RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);

requestQueue.addRequestFinishedListener(new RequestQueue.RequestFinishedListener<Object>() {
            @Override
            public void onRequestFinished(Request<Object> request) {
                requestQueue.getCache().clear();
            }
        });

0
我试图使用remove(key)从缓存中删除位图,但它没有起作用,所以我检查了putBitmap(String url, Bitmap bitmap)接收到的URL。我发现URL有一些前缀,例如#W0#H#S7http...,这是因为Volley为每个URL调用getCacheKey(String url, int maxWidth, int maxHeight, ScaleType scaleType)。因此,如果您想从缓存中删除URL,则还必须调用此函数以获取URL的键。
 String key = mImageLoader.getCacheKey(url, 0, 0, ImageView.ScaleType.CENTER_INSIDE);

 mRequestQueue.getCache().remove(key);

如果您使用imageLoader.get(String requestUrl,ImageLoader.ImageListener listener),请传递0,0和ImageView.ScaleType.CENTER_INSIDE,否则请传递最小高度、宽度和比例类型。

注意:getCacheKey()是ImageLoader类的私有函数,因此您必须将其更改为公共函数以在应用程序内部使用它。


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