经过学习,我们知道Volley的架构如下:
从架构上我们可以看到,volley有设置缓存机制,当找不到数据缓存或数据缓存过期时,才会联网获取新的数据。Volley 本身有缓存机制,不仅仅默认缓存图片,也有缓存Json数据。通过手机文件管理软件,我们发现Volley缓存地址:/data/data/软件包/cache/volley 目录下。
那么,在联网获取了数据缓存后,如何获取到Volley缓存中的数据呢?在百度上找了一整天的资料都没有说明如何获取到最新的数据。最后还是再stack overflow中找到了相关的资料。
RequestQueue类中有一个子函数getCache()可以返回Cache实例,通过调用改实例中的get(url)函数可以查看手机磁盘中是否保存有缓存数据,其成员变量data保存着缓存的数据内容。即:queue.getCache().get(url).data
所以,我们可以通过以下语句,来选择获取缓存数据或者向服务器获取最新数据。
1
2
3
4
5
6
7
|
if
(queue.getCache().get(url)!=
null
){
//response exists
String cachedResponse =
new
String(queue.getCache().get(url).data);
}
else
{
//no response
queue.add(stringRequest);
}
|
其实这样做还是有缺陷的,那就是如果服务器更新了数据的话,则我们客户端没办法获取最新数据,而是从缓存中调取缓存数据。
为此,我一个比较笨的方法是:判断网络是否可用,如果可用则更新数据,当网络不可用时,采用缓存数据。
1
2
3
4
5
6
7
|
Context context = getActivity().getApplicationContext();
if
(!isNetworkAvailable(context)){
getFromDiskCache(url);
//如果没网,则调取缓存数据
}
else
{
//有网则从网上更新数据
//……(省略)
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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为例):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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 block
e.printStackTrace();
}
}
else
{
Log.d(TAG, 没有缓存数据);
}
}
|
其实这是比较笨的办法,按道理应该是向服务器请求,看是否有数据更新,有则更新数据(即服务器决定缓存是否可用)但是暂时不知道怎么完成,等以后再改吧。