【发布时间】:2016-07-30 13:41:54
【问题描述】:
我有一个 Volley 适配器来处理 HTTP 请求,使用 OKhttp3 作为传输,DiskBasedCache 作为缓存实现。
我正在尝试使用 .remove(url) 从缓存中删除特定的 JSON 提要请求,但它不起作用。这是一个示例代码:
在活动中提出请求:
String url = "http://somewebsite.com/feed.json"
VolleyStringRequest stringRequest = new VolleyStringRequest(Method.GET,null, url,responseListener(),errorListener());
RequestQueue queue = CustomVolleyRequestQueue.getInstance(context).getRequestQueue();
queue.add(stringRequest);
完成某事后删除缓存:
Cache cache = CustomVolleyRequestQueue.getInstance(context).getRequestQueue().getCache();
Cache.Entry cacheEntry = cache.get(url);
if (cacheEntry != null) {
Log.d("cache", "has_cache");
} else {
Log.d("cache", "no cache");
}
cache.remove(url);
但是,在 logCat 中,键 url 返回“无缓存”,而 cache.remove(url) 产生
DiskBasedCache.remove: Could not delete cache entry for key=http://somewebsite.com/feed.json,
filename=-159673043453434434
有人知道如何使用cache.remove(url)吗? Volley 是否使用 url 作为缓存条目的键?我不想使用cache.clear(),而只是删除特定的请求缓存。
CustomVolleyRequestQueue:
public class CustomVolleyRequestQueue {
private static CustomVolleyRequestQueue mInstance;
private static Context mCtx;
private RequestQueue mRequestQueue;
private CustomVolleyRequestQueue(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
}
public static synchronized CustomVolleyRequestQueue getInstance(Context context) {
if (mInstance == null) {
mInstance = new CustomVolleyRequestQueue(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
Cache cache = new DiskBasedCache(mCtx.getCacheDir(), 10 * 1024 * 1024);
Network network = new BasicNetwork(new OkHttpStack());
mRequestQueue = new RequestQueue(cache, network);
// Don't forget to start the volley request queue
mRequestQueue.start();
}
return mRequestQueue;
}
}
更新:我创建了一个扩展 DiskBasedCache 的自定义类,以检查它用于缓存的键。
public class CustomDiskBasedCache extends DiskBasedCache {
public CustomDiskBasedCache(File rootDirectory, int maxCacheSizeInBytes) {
super(rootDirectory, maxCacheSizeInBytes);
}
@Override
public synchronized void put(String key, Entry entry) {
super.put( key, entry);
Log.d("cache_key",key);
}
}
看起来每个缓存键都以0:为前缀,例如:
0:http://somewebsite.com/feed.json
我不知道为什么要添加它。
【问题讨论】:
标签: java android caching android-volley