Android的安装抽射缓存使用

Android的安装抽射缓存使用

本文介绍了Android的安装抽射缓存使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建和使用一个缓存服务器JSON响应。

例如:

缓存JSON对象到内部存储器和使用,当我们没有互联网连接。

在下面的示例code,我找不到有关如何使用排球缓存任何文件和重用,当再次更新服务器头不会过期。

是这样的:设置期满头,并使用高速缓存,并尝试期满后重新装入

我想设置的缓存机制,这个方法:

 私人无效makeJsonArryReq(){
    JsonArrayRequest REQ =新JsonArrayRequest(Const.URL_JSON_ARRAY,
            新Response.Listener< JSONArray>(){
                @覆盖
                公共无效onResponse(JSONArray响应){
                    msgResponse.setText(response.toString());
                }
            },新Response.ErrorListener(){
        @覆盖
        公共无效onErrorResponse(VolleyError错误){
        }
    });
    。AppController.getInstance()addToRequestQueue(REQ,tag_json_arry);
}
 

缓存方式:

 公共静态Cache.Entry parseIgnoreCacheHeaders(NetworkResponse响应){
    长今= System.currentTimeMillis的();

    地图<字符串,字符串>标题= response.headers;
    长serverDate = 0;
    字符串serverEtag = NULL;
    字符串headerValue;

    headerValue = headers.get(日期);
    如果(headerValue!= NULL){
        serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
    }

    serverEtag = headers.get(ETag的);

    最终长cacheHitButRefreshed = 3 * 60 * 1000; //在3分钟内缓存将受到较大冲击,同时也刷新的背景
    最终长cacheExpired = 24 * 60 * 60 * 1000; //在24小时内这个缓存条目完全失效
    最终长softExpire =现在+ cacheHitButRefreshed;
    最终长TTL =现在+ cacheExpired;

    Cache.Entry进入=新Cache.Entry();
    entry.data = response.data;
    entry.etag = serverEtag;
    entry.softTtl = softExpire;
    entry.ttl = TTL;
    entry.serverDate = serverDate;
    entry.responseHeaders =头;

    返回入境;
}
 

解决方案

因为我无法找到 parseIgnoreCacheHeaders 所以我用一些codeS里面的 parseCacheHeaders (和。参见@ oleksandr_yefremov codeS的)对你的情况。下面code我已经测试。当然,能也使用了 JsonArrayRequest。希望这有助于!

  JsonObjectRequest jsonObjectRequest =新JsonObjectRequest(0,mUrl,新Response.Listener<的JSONObject>(){
        @覆盖
        公共无效onResponse(JSONObject的响应){
            尝试 {
                mTextView.setText(response.toString(5));
            }赶上(JSONException E){
                mTextView.setText(e.toString());
            }
        }
    },新Response.ErrorListener(){
        @覆盖
        公共无效onErrorResponse(VolleyError错误){

        }
    }){
        @覆盖
        受保护的响应和LT;的JSONObject> parseNetworkResponse(NetworkResponse响应){
            尝试 {
                Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(响应);
                如果(cacheEntry == NULL){
                    cacheEntry =新Cache.Entry();
                }
                最终长cacheHitButRefreshed = 3 * 60 * 1000; //在3分钟内缓存将受到较大冲击,同时也刷新的背景
                最终长cacheExpired = 24 * 60 * 60 * 1000; //在24小时内这个缓存条目完全失效
                长今= System.currentTimeMillis的();
                最终长softExpire =现在+ cacheHitButRefreshed;
                最终长TTL =现在+ cacheExpired;
                cacheEntry.data = response.data;
                cacheEntry.softTtl = softExpire;
                cacheEntry.ttl = TTL;
                字符串headerValue;
                headerValue = response.headers.get(日期);
                如果(headerValue!= NULL){
                    cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
                }
                headerValue = response.headers.get(上次修改);
                如果(headerValue!= NULL){
                    cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);
                }
                cacheEntry.responseHeaders = response.headers;
                最后弦乐jsonString =新的String(response.data,
                        HttpHeaderParser.parseCharset(response.headers));
                返回Response.success(新的JSONObject(jsonString),cacheEntry);
            }赶上(UnsupportedEncodingException E){
                返回Response.error(新ParseError(e)条);
            }赶上(JSONException E){
                返回Response.error(新ParseError(e)条);
            }
        }

        @覆盖
        保护无效deliverResponse(JSONObject的响应){
            super.deliverResponse(响应);
        }

        @覆盖
        公共无效deliverError(VolleyError错误){
            super.deliverError(错误);
        }

        @覆盖
        保护VolleyError parseNetworkError(VolleyError volleyError){
            返回super.parseNetworkError(volleyError);
        }
    };

    MySingleton.getInstance(本).addToRequestQueue(jsonObjectRequest);
 


更新

如果你想有一个基类,请参阅以下codeS:

 公共类CacheRequest扩展请求< NetworkResponse> {
    私人最终Response.Listener< NetworkResponse> mListener;
    私人最终Response.ErrorListener mErrorListener;

    公共CacheRequest(INT方法,字符串URL,Response.Listener< NetworkResponse>听者,Response.ErrorListener errorListener){
        超(方法,URL,errorListener);
        this.mListener =侦听器;
        this.mErrorListener = errorListener;
    }


    @覆盖
    受保护的响应和LT; NetworkResponse> parseNetworkResponse(NetworkResponse响应){
        Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(响应);
        如果(cacheEntry == NULL){
            cacheEntry =新Cache.Entry();
        }
        最终长cacheHitButRefreshed = 3 * 60 * 1000; //在3分钟内缓存将受到较大冲击,同时也刷新的背景
        最终长cacheExpired = 24 * 60 * 60 * 1000; //在24小时内这个缓存条目完全失效
        长今= System.currentTimeMillis的();
        最终长softExpire =现在+ cacheHitButRefreshed;
        最终长TTL =现在+ cacheExpired;
        cacheEntry.data = response.data;
        cacheEntry.softTtl = softExpire;
        cacheEntry.ttl = TTL;
        字符串headerValue;
        headerValue = response.headers.get(日期);
        如果(headerValue!= NULL){
            cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
        }
        headerValue = response.headers.get(上次修改);
        如果(headerValue!= NULL){
            cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);
        }
        cacheEntry.responseHeaders = response.headers;
        返回Response.success(响应,cacheEntry);
    }

    @覆盖
    保护无效deliverResponse(NetworkResponse响应){
        mListener.onResponse(响应);
    }

    @覆盖
    保护VolleyError parseNetworkError(VolleyError volleyError){
        返回super.parseNetworkError(volleyError);
    }

    @覆盖
    公共无效deliverError(VolleyError错误){
        mErrorListener.onErrorResponse(错误);
    }
}
 

然后在MainActivity,你可以这样调用

  CacheRequest cacheRequest =新CacheRequest(0,mUrl,新Response.Listener< NetworkResponse>(){
        @覆盖
        公共无效onResponse(NetworkResponse响应){
            尝试 {
                最后弦乐jsonString =新的String(response.data,
                        HttpHeaderParser.parseCharset(response.headers));
                的JSONObject的JSONObject =新的JSONObject(jsonString);
                mTextView.setText(jsonObject.toString(5));
            }赶上(UnsupportedEncodingException | JSONException E){
                e.printStackTrace();
            }
        }
    },新Response.ErrorListener(){
        @覆盖
        公共无效onErrorResponse(VolleyError错误){
            mTextView.setText(error.toString());
        }
    });

    MySingleton.getInstance(本).addToRequestQueue(cacheRequest);
 


更新了完整的源$ C ​​$ C:

MainActivity.java:

 包com.example.cachevolley;

进口android.content.Context;
进口android.os.Bundle;
进口android.support.v7.app.AppCompatActivity;
进口android.view.Menu;
进口android.view.MenuItem;
进口android.widget.TextView;
进口android.widget.Toast;

进口com.android.volley.Cache;
进口com.android.volley.NetworkResponse;
进口com.android.volley.Request;
进口com.android.volley.RequestQueue;
进口com.android.volley.Response;
进口com.android.volley.VolleyError;
进口com.android.volley.toolbox.HttpHeaderParser;
进口com.android.volley.toolbox.Volley;

进口org.json.JSONException;
进口org.json.JSONObject;

进口java.io.UnsupportedEncodingException;

公共类MainActivity扩展AppCompatActivity {

    私人最终上下文mContext =这一点;

    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);

        最后的TextView的TextView =(TextView中)findViewById(R.id.textView);

        请求队列排队= Volley.newRequestQueue(本);
        字符串URL =htt​​p://192.168.0.100/apitest;

        CacheRequest cacheRequest =新CacheRequest(0,网址,新Response.Listener< NetworkResponse>(){
            @覆盖
            公共无效onResponse(NetworkResponse响应){
                尝试 {
                    最后弦乐jsonString =新的String(response.data,
                            HttpHeaderParser.parseCharset(response.headers));
                    的JSONObject的JSONObject =新的JSONObject(jsonString);
                    textView.setText(jsonObject.toString(5));
                    Toast.makeText(mContext,onResponse:\ñ\ N+ jsonObject.toString(),Toast.LENGTH_SHORT).show();
                }赶上(UnsupportedEncodingException | JSONException E){
                    e.printStackTrace();
                }
            }
        },新Response.ErrorListener(){
            @覆盖
            公共无效onErrorResponse(VolleyError错误){
                Toast.makeText(mContext,onErrorResponse:\ñ\ N+ error.toString(),Toast.LENGTH_SHORT).show();
            }
        });

        //增加请求到请求队列。
        queue.add(cacheRequest);
    }

    @覆盖
    公共布尔onCreateOptionsMenu(功能菜单){
        //充气菜单;这增加了项目操作栏,如果它是present。
        。getMenuInflater()膨胀(R.menu.menu_main,菜单);
        返回true;
    }

    @覆盖
    公共布尔onOptionsItemSelected(菜单项项){
        //处理动作栏项目点击这里。将操作栏
        //自动在主/向上按钮操作的点击,只要
        //你在AndroidManifest.xml中指定一个父活动。
        INT的id = item.getItemId();

        // noinspection SimplifiableIfStatement
        如果(ID == R.id.action_settings){
            返回true;
        }

        返回super.onOptionsItemSelected(项目);
    }

    私有类CacheRequest扩展请求< NetworkResponse> {
        私人最终Response.Listener< NetworkResponse> mListener;
        私人最终Response.ErrorListener mErrorListener;

        公共CacheRequest(INT方法,字符串URL,Response.Listener< NetworkResponse>听者,Response.ErrorListener errorListener){
            超(方法,URL,errorListener);
            this.mListener =侦听器;
            this.mErrorListener = errorListener;
        }


        @覆盖
        受保护的响应和LT; NetworkResponse> parseNetworkResponse(NetworkResponse响应){
            Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(响应);
            如果(cacheEntry == NULL){
                cacheEntry =新Cache.Entry();
            }
            最终长cacheHitButRefreshed = 3 * 60 * 1000; //在3分钟内缓存将受到较大冲击,同时也刷新的背景
            最终长cacheExpired = 24 * 60 * 60 * 1000; //在24小时内这个缓存条目完全失效
            长今= System.currentTimeMillis的();
            最终长softExpire =现在+ cacheHitButRefreshed;
            最终长TTL =现在+ cacheExpired;
            cacheEntry.data = response.data;
            cacheEntry.softTtl = softExpire;
            cacheEntry.ttl = TTL;
            字符串headerValue;
            headerValue = response.headers.get(日期);
            如果(headerValue!= NULL){
                cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
            }
            headerValue = response.headers.get(上次修改);
            如果(headerValue!= NULL){
                cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);
            }
            cacheEntry.responseHeaders = response.headers;
            返回Response.success(响应,cacheEntry);
        }

        @覆盖
        保护无效deliverResponse(NetworkResponse响应){
            mListener.onResponse(响应);
        }

        @覆盖
        保护VolleyError parseNetworkError(VolleyError volleyError){
            返回super.parseNetworkError(volleyError);
        }

        @覆盖
        公共无效deliverError(VolleyError错误){
            mErrorListener.onErrorResponse(错误);
        }
    }
}
 

清单文件:

 < XML版本=1.0编码=UTF-8&GT?;
<舱单的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    包=com.example.cachevolley>

    <使用-权限的Andr​​oid:名称=android.permission.INTERNET对/>

    <应用
        机器人:allowBackup =真
        机器人:图标=@纹理映射/ ic_launcher
        机器人:标签=@字符串/ APP_NAME
        机器人:主题=@风格/ AppTheme>
        <活动
            机器人:名称=。MainActivity
            机器人:标签=@字符串/ APP_NAME>
            <意向滤光器>
                <作用机器人:名称=android.intent.action.MAIN/>

                <类机器人:名称=android.intent.category.LAUNCHER/>
            &所述; /意图滤光器>
        < /活性GT;
    < /用途>

< /舱单>
 

版式文件:

 < RelativeLayout的的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    的xmlns:工具=htt​​p://schemas.android.com/tool​​s
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:paddingBottom会=@扪/ activity_vertical_margin
    机器人:以下属性来=@扪/ activity_horizo​​ntal_margin
    机器人:paddingRight =@扪/ activity_horizo​​ntal_margin
    机器人:paddingTop =@扪/ activity_vertical_margin
    工具:上下文=MainActivity。>

    <的TextView
        机器人:ID =@ + ID / TextView的
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:文本=@字符串/参考hello world/>

< / RelativeLayout的>
 

I'm trying to create and use a cache for a server JSON response.

For example:

cache JSON objects to internal memory and use that when we don't have an internet connection.

In the following sample code, I can not find any document about how to cache it with Volley and reuse that when server header for update again don't expire.

Like this: set expiration to header and use cache and try to load again after expiration.

I'm trying to set cache mechanism for this method:

private void makeJsonArryReq() {
    JsonArrayRequest req = new JsonArrayRequest(Const.URL_JSON_ARRAY,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    msgResponse.setText(response.toString());
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
        }
    });
    AppController.getInstance().addToRequestQueue(req,tag_json_arry);
}

Cache method:

public static Cache.Entry parseIgnoreCacheHeaders(NetworkResponse response) {
    long now = System.currentTimeMillis();

    Map<String, String> headers = response.headers;
    long serverDate = 0;
    String serverEtag = null;
    String headerValue;

    headerValue = headers.get("Date");
    if (headerValue != null) {
        serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
    }

    serverEtag = headers.get("ETag");

    final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background
    final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely
    final long softExpire = now + cacheHitButRefreshed;
    final long ttl = now + cacheExpired;

    Cache.Entry entry = new Cache.Entry();
    entry.data = response.data;
    entry.etag = serverEtag;
    entry.softTtl = softExpire;
    entry.ttl = ttl;
    entry.serverDate = serverDate;
    entry.responseHeaders = headers;

    return entry;
}
解决方案

Since I cannot find parseIgnoreCacheHeaders so I use some codes inside parseCacheHeaders (and refering to @oleksandr_yefremov's codes) for your case. The following code I have tested. Of course, can use for JsonArrayRequest also. Hope this help!

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(0, mUrl, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                mTextView.setText(response.toString(5));
            } catch (JSONException e) {
                mTextView.setText(e.toString());
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }) {
        @Override
        protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
            try {
                Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);
                if (cacheEntry == null) {
                    cacheEntry = new Cache.Entry();
                }
                final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background
                final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely
                long now = System.currentTimeMillis();
                final long softExpire = now + cacheHitButRefreshed;
                final long ttl = now + cacheExpired;
                cacheEntry.data = response.data;
                cacheEntry.softTtl = softExpire;
                cacheEntry.ttl = ttl;
                String headerValue;
                headerValue = response.headers.get("Date");
                if (headerValue != null) {
                    cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
                }
                headerValue = response.headers.get("Last-Modified");
                if (headerValue != null) {
                    cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);
                }
                cacheEntry.responseHeaders = response.headers;
                final String jsonString = new String(response.data,
                        HttpHeaderParser.parseCharset(response.headers));
                return Response.success(new JSONObject(jsonString), cacheEntry);
            } catch (UnsupportedEncodingException e) {
                return Response.error(new ParseError(e));
            } catch (JSONException e) {
                return Response.error(new ParseError(e));
            }
        }

        @Override
        protected void deliverResponse(JSONObject response) {
            super.deliverResponse(response);
        }

        @Override
        public void deliverError(VolleyError error) {
            super.deliverError(error);
        }

        @Override
        protected VolleyError parseNetworkError(VolleyError volleyError) {
            return super.parseNetworkError(volleyError);
        }
    };

    MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);


UPDATE:

If you want a base class, refer to the following codes:

public class CacheRequest extends Request<NetworkResponse> {
    private final Response.Listener<NetworkResponse> mListener;
    private final Response.ErrorListener mErrorListener;

    public CacheRequest(int method, String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        this.mListener = listener;
        this.mErrorListener = errorListener;
    }


    @Override
    protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
        Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);
        if (cacheEntry == null) {
            cacheEntry = new Cache.Entry();
        }
        final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background
        final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely
        long now = System.currentTimeMillis();
        final long softExpire = now + cacheHitButRefreshed;
        final long ttl = now + cacheExpired;
        cacheEntry.data = response.data;
        cacheEntry.softTtl = softExpire;
        cacheEntry.ttl = ttl;
        String headerValue;
        headerValue = response.headers.get("Date");
        if (headerValue != null) {
            cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
        }
        headerValue = response.headers.get("Last-Modified");
        if (headerValue != null) {
            cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);
        }
        cacheEntry.responseHeaders = response.headers;
        return Response.success(response, cacheEntry);
    }

    @Override
    protected void deliverResponse(NetworkResponse response) {
        mListener.onResponse(response);
    }

    @Override
    protected VolleyError parseNetworkError(VolleyError volleyError) {
        return super.parseNetworkError(volleyError);
    }

    @Override
    public void deliverError(VolleyError error) {
        mErrorListener.onErrorResponse(error);
    }
}

Then in MainActivity, you can call like this

CacheRequest cacheRequest = new CacheRequest(0, mUrl, new Response.Listener<NetworkResponse>() {
        @Override
        public void onResponse(NetworkResponse response) {
            try {
                final String jsonString = new String(response.data,
                        HttpHeaderParser.parseCharset(response.headers));
                JSONObject jsonObject = new JSONObject(jsonString);
                mTextView.setText(jsonObject.toString(5));
            } catch (UnsupportedEncodingException | JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            mTextView.setText(error.toString());
        }
    });

    MySingleton.getInstance(this).addToRequestQueue(cacheRequest);


UPDATE WITH FULL SOURCE CODE:

MainActivity.java:

package com.example.cachevolley;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Cache;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;

public class MainActivity extends AppCompatActivity {

    private final Context mContext = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final TextView textView = (TextView) findViewById(R.id.textView);

        RequestQueue queue = Volley.newRequestQueue(this);
        String url = "http://192.168.0.100/apitest";

        CacheRequest cacheRequest = new CacheRequest(0, url, new Response.Listener<NetworkResponse>() {
            @Override
            public void onResponse(NetworkResponse response) {
                try {
                    final String jsonString = new String(response.data,
                            HttpHeaderParser.parseCharset(response.headers));
                    JSONObject jsonObject = new JSONObject(jsonString);
                    textView.setText(jsonObject.toString(5));
                    Toast.makeText(mContext, "onResponse:\n\n" + jsonObject.toString(), Toast.LENGTH_SHORT).show();
                } catch (UnsupportedEncodingException | JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(mContext, "onErrorResponse:\n\n" + error.toString(), Toast.LENGTH_SHORT).show();
            }
        });

        // Add the request to the RequestQueue.
        queue.add(cacheRequest);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private class CacheRequest extends Request<NetworkResponse> {
        private final Response.Listener<NetworkResponse> mListener;
        private final Response.ErrorListener mErrorListener;

        public CacheRequest(int method, String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
            super(method, url, errorListener);
            this.mListener = listener;
            this.mErrorListener = errorListener;
        }


        @Override
        protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
            Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);
            if (cacheEntry == null) {
                cacheEntry = new Cache.Entry();
            }
            final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background
            final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely
            long now = System.currentTimeMillis();
            final long softExpire = now + cacheHitButRefreshed;
            final long ttl = now + cacheExpired;
            cacheEntry.data = response.data;
            cacheEntry.softTtl = softExpire;
            cacheEntry.ttl = ttl;
            String headerValue;
            headerValue = response.headers.get("Date");
            if (headerValue != null) {
                cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
            }
            headerValue = response.headers.get("Last-Modified");
            if (headerValue != null) {
                cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);
            }
            cacheEntry.responseHeaders = response.headers;
            return Response.success(response, cacheEntry);
        }

        @Override
        protected void deliverResponse(NetworkResponse response) {
            mListener.onResponse(response);
        }

        @Override
        protected VolleyError parseNetworkError(VolleyError volleyError) {
            return super.parseNetworkError(volleyError);
        }

        @Override
        public void deliverError(VolleyError error) {
            mErrorListener.onErrorResponse(error);
        }
    }
}

Manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.cachevolley" >

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Layout file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

这篇关于Android的安装抽射缓存使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 19:53