Android Volley 获取磁盘已有缓存数据

来源:互联网 发布:淘宝店铺运营助手工资 编辑:程序博客网 时间:2024/06/06 03:13

经过学习,我们知道Volley的架构如下:


从架构上我们可以看到,volley有设置缓存机制,当找不到数据缓存或数据缓存过期时,才会联网获取新的数据。Volley 本身有缓存机制,不仅仅默认缓存图片,也有缓存Json数据。通过手机文件管理软件,我们发现Volley缓存地址:/data/data/软件包/cache/volley 目录下。

那么,在联网获取了数据缓存后,如何获取到Volley缓存中的数据呢?在百度上找了一整天的资料都没有说明如何获取到最新的数据。最后还是再stack overflow中找到了相关的资料。

RequestQueue类中有一个子函数getCache()可以返回Cache实例,通过调用改实例中的get(url)函数可以查看手机磁盘中是否保存有缓存数据,其成员变量data保存着缓存的数据内容。即:queue.getCache().get(url).data

所以,我们可以通过以下语句,来选择获取缓存数据或者向服务器获取最新数据。

if(queue.getCache().get(url)!=null){  //response exists  String cachedResponse = new String(queue.getCache().get(url).data);}else{  //no response  queue.add(stringRequest);}


其实这样做还是有缺陷的,那就是如果服务器更新了数据的话,则我们客户端没办法获取最新数据,而是从缓存中调取缓存数据。

为此,我一个比较笨的方法是:判断网络是否可用,如果可用则更新数据,当网络不可用时,采用缓存数据。

Context context = getActivity().getApplicationContext();if(!isNetworkAvailable(context)){getFromDiskCache(url);     //如果没网,则调取缓存数据}else{//有网则从网上更新数据 //……(省略)}
其中isNetworkAvailable()函数用于判断网络是否可用:

public static boolean isNetworkAvailable(Context context) {   try {ConnectivityManager manger = (ConnectivityManager) context                .getSystemService(Context.CONNECTIVITY_SERVICE);         NetworkInfo info = manger.getActiveNetworkInfo();        //return (info!=null && info.isConnected());        if(info != null){        return info.isConnected();        }else{        return false;        }} catch (Exception e) {        return false;}}

getFromDiskCache()函数用于获取缓存数据(以JSONArray为例):

private void getFromDiskCache(String url) {if(mQueue.getCache().get(url)!=null){try {String str = new String((mQueue.getCache().get(url).data);JSONArray response = new JSONArray(str);//……(省略操作)} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}}else{Log.d(TAG, "没有缓存数据");  }}
其实,在服务器没响应时,我们也可以调用getFromDiskCache()函数来调取缓存数据的,在public void onErrorResponse(VolleyError error) { }中增加相应语句即可,这里不做展开。


其实这是比较笨的办法,按道理应该是向服务器请求,看是否有数据更新,有则更新数据(即服务器决定缓存是否可用)但是暂时不知道怎么完成,等以后再改吧。


参考链接:

http://stackoverflow.com/questions/21902063/volley-how-to-cache-loaded-data-to-disk-and-load-them-when-no-connection-avail

1 0
原创粉丝点击