·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> Android开发 >> Android实现离线缓存的方法

Android实现离线缓存的方法

作者:佚名      Android开发编辑:admin      更新时间:2022-07-23

 离线缓存就是在网络畅通的情况下将从服务器收到的数据保存到本地,当网络断开之后直接读取本地文件中的数据。如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,依然应该使用文件缓存或数据库缓存。

以上内容是小编给大家介绍的Android实现离线缓存的方法,希望对大家有所帮助!