如何使凌空缓存在1分钟内到期

时间:2016-05-01 12:29:29

标签: android android-volley

我遇到了Volley缓存问题。有什么办法可以在一分钟后删除缓存并让它请求新数据吗?

我的代码

    JsonObjectRequest jsObjRequest = new JsonObjectRequest
        (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

    @Override
    public void onResponse(JSONObject response) {
        mTxtDisplay.setText("Response: " + response.toString());
    }
}, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
        // TODO Auto-generated method stub

    }
});

1 个答案:

答案 0 :(得分:2)

你可以这样做:

 JsonObjectRequest jsObjRequest = new JsonObjectRequest
        (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

    @Override
    public void onResponse(JSONObject response) {
        mTxtDisplay.setText("Response: " + response.toString());
    }
}, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
        // TODO Auto-generated method stub

    }
}){
 @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        Response<JSONObject> resp = super.parseNetworkResponse(response);
        if(!resp.isSuccess()) {
            return resp;
        }
        long now = System.currentTimeMillis();
        Cache.Entry entry = resp.cacheEntry;
        if(entry == null) {
            entry = new Cache.Entry();
            entry.data = response.data;
            entry.responseHeaders = response.headers;
        }
        entry.ttl = now + 60 * 1000;  //keeps cache for 1 min

        return Response.success(resp.result, entry);
    }
};

这将始终为您的请求缓存,仅持续1分钟