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

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

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

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

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

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

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. if(queue.getCache().get(url)!=null){  
  2.   //response exists  
  3.   String cachedResponse = new String(queue.getCache().get(url).data);  
  4. }else{  
  5.   //no response  
  6.   queue.add(stringRequest);  
  7. }  

 

 

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

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

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. Context context = getActivity().getApplicationContext();  
  2. if(!isNetworkAvailable(context)){  
  3.     getFromDiskCache(url);               //如果没网,则调取缓存数据  
  4. }else{  
  5. //有网则从网上更新数据                   
  6. //……(省略)  
  7. }  

其中isNetworkAvailable()函数用于判断网络是否可用:

 

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. public static boolean isNetworkAvailable(Context context) {     
  2.     try {  
  3.         ConnectivityManager manger = (ConnectivityManager) context  
  4.                 .getSystemService(Context.CONNECTIVITY_SERVICE);   
  5.         NetworkInfo info = manger.getActiveNetworkInfo();  
  6.         //return (info!=null && info.isConnected());  
  7.         if(info != null){  
  8.             return info.isConnected();  
  9.         }else{  
  10.             return false;  
  11.         }  
  12.     } catch (Exception e) {  
  13.         return false;  
  14.     }  
  15. }  


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

 

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. private void getFromDiskCache(String url) {  
  2.     if(mQueue.getCache().get(url)!=null){  
  3.         try {  
  4.             String str = new String((mQueue.getCache().get(url).data);  
  5.             JSONArray response = new JSONArray(str);  
  6.             //……(省略操作)  
  7.         } catch (JSONException e) {  
  8.             // TODO Auto-generated catch block  
  9.             e.printStackTrace();  
  10.         }  
  11.     }else{  
  12.         Log.d(TAG, "没有缓存数据");    
  13.     }  
  14. }  

其实,在服务器没响应时,我们也可以调用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

posted @ 2017-05-10 09:52  天涯海角路  阅读(207)  评论(0)    收藏  举报