如何自动清除凌空缓存?

Joh*_*ody 12 android caching android-volley

我想每30分钟清除一次请求队列.

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

通过扩展凌空缓存类来覆盖方法?

或者构建一个计时器,每次我需要清除缓存?

Gir*_*hai 20

Google Volley提供了两种清除缓存中项目的方法:

AppController.getInstance().getRequestQueue().getCache().remove(key);
Run Code Online (Sandbox Code Playgroud)

AppController.getInstance().getRequestQueue().getCache().invalidate(key, fullExpire);
Run Code Online (Sandbox Code Playgroud)

删除意味着您要删除实际的缓存数据.

无效意味着您只是将数据标记为无效.因此,凌空将检查服务器数据是否仍然有效.该全过期确定是否使用数据之前凌空已与服务器验证它.

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

您可以使用volley的serverDate来获取最初收到响应的日期

AppController.getInstance().getRequestQueue().getCache().get(url).serverDate
Run Code Online (Sandbox Code Playgroud)

所以在你的代码中使用getMinutesDifference函数作为

  public static long getMinutesDifference(long timeStart,long timeStop){
            long diff = timeStop - timeStart;
            long diffMinutes = diff / (60 * 1000);

            return  diffMinutes;
        }
Run Code Online (Sandbox Code Playgroud)

并在您的代码中调用此函数

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);
}
Run Code Online (Sandbox Code Playgroud)

如果先前的url响应> = 30分钟,它将使缓存无效.