Android 离线缓存的快速实现

来源:互联网 发布:菲尼克斯之光 知乎 编辑:程序博客网 时间:2024/05/22 08:20

离线缓存是指在有网络的状态下将从服务器获取的网络数据,如Json 数据缓存到本地,在断网的状态下启动APP时读取本地缓存数据显示在界面上,常用的APP(网易新闻、知乎等等)都是支持离线缓存的,这样带来了更好的用户体验。

如果能够在调用网络接口后自动缓存返回的Json数据,下次在断网状态下调用这个接口获取到缓存的Json数据的话,那该多好呢?Volley做到了这一点。

因此,今天这篇文章介绍的就是使用Volley自带的数据缓存,配合Universal-ImageLoader的图片缓存,实现断网状态下的图文显示。

实现效果

这里写图片描述

如何实现?

1.使用Volley访问网络接口

 /**     * 获取网络数据     */    private void getData() {        StringRequest stringRequest = new StringRequest(Request.Method.POST, TEST_API, new Response.Listener<String>() {            @Override            public void onResponse(String s) {                textView.setText("data from Internet: " + s);                try {                    JSONObject jsonObject = new JSONObject(s);                    JSONArray resultList = jsonObject.getJSONArray("resultList");                    JSONObject JSONObject = (org.json.JSONObject) resultList.opt(0);                    String head_img = JSONObject.getString("head_img");                    ImageLoader.getInstance().displayImage(head_img, imageView);                } catch (JSONException e) {                    e.printStackTrace();                }            }        }, new Response.ErrorListener() {            @Override            public void onErrorResponse(VolleyError volleyError) {            }        }) {            @Override            protected Map<String, String> getParams() throws AuthFailureError {                Map<String, String> map = new HashMap<String, String>();                map.put("phone", "15962203803");                map.put("password", "123456");                return map;            }        };        queue.add(stringRequest);    }

当接口访问成功以后,Volley会自动缓存此次纪录在/data/data/{package name}/cache/volley文件夹中。
这里写图片描述
打开上面的文件,可以发现接口的路径和返回值都被保存在该文件里面了。
这里写图片描述
当在断网状态时,如何获取到该接口的缓存的返回值呢?
使用RequestQueue提供的getCache()方法查询该接口的缓存数据

 if (queue.getCache().get(TEST_API) != null) {                        String cachedResponse = new String(queue.getCache().get(TEST_API).data);

2.使用Universal-ImageLoader加载图片

ImageLoader.getInstance().displayImage(head_img, imageView);

注意点

1.观察上面的缓存文件可以发现,Volley只缓存了接口路径,并没有缓存接口的传入参数,因此如果做分页查询的话,使用此方法是不妥的。
2.在测试过程中,依然发现有的时候获取不到缓存数据,有的时候却可以获取到。对获取缓存的代码延迟加载能够有效解决这个问题。
3.如果考虑到缓存的过期策略,可以使用更好的ASimpleCache框架辅助开发。对缓存有更高要求的APP,依然应该使用文件缓存或数据库缓存。

源代码下载

13 0
原创粉丝点击