Volley在没有网的情况下使用磁盘缓存的数据
2015-09-28 16:05
477 查看
使用Volley的应该都知道,Volley中的缓存机制是基于http cache的,简单来说就是它的缓存是依赖于服务器的。但是一般没有网时我们打开app,还是会展示最近一次展示的内容,所以,需要对它进行一下修改。
最开始想的是在CacheDispatcher中的run()中这样修改一下。但是一直不知道怎么来判断网络情况,所以这样的方法应该是不行的。
自定义一个StringRequest
Http缓存机制的概念
最开始想的是在CacheDispatcher中的run()中这样修改一下。但是一直不知道怎么来判断网络情况,所以这样的方法应该是不行的。
Cache.Entry entry = mCache.get(request.getCacheKey()); if (entry == null) { request.addMarker("cache-miss"); // Cache miss; send off to the network dispatcher. mNetworkQueue.put(request); continue; } // 如果没有网络则直接将从磁盘中取到的数据进行解析,这里似乎无法来判断网络的情况 // if(true) // { // Response<?> response = request.parseNetworkResponse( // new NetworkResponse(entry.data, entry.responseHeaders)); // mDelivery.postResponse(request, response); // }然后思考一下,没网并且如果时间是超过了http cache缓存机制的时间话,那么出现的结果是会调用ErrorListener,从而可以找到是需要修改deliverError,deliverError则是在Request.java中的一个方法,那么最简单的方法就是自定义一个Request。
自定义一个StringRequest
public class MyStringRequest extends StringRequest { public MyStringRequest(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) { super(method, url, listener, errorListener); } @Override public void deliverError(VolleyError error) { if (error instanceof NoConnectionError) { Cache.Entry entry = this.getCacheEntry(); if(entry != null) { Response<String> response = parseNetworkResponse(new NetworkResponse(entry.data, entry.responseHeaders)); deliverResponse(response.result); return; } } super.deliverError(error); } }自定义一个JsonObjectRequest
public class MyJsonObjectRequest extends JsonObjectRequest { public MyJsonObjectRequest(int method, String url, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) { super(method, url, listener, errorListener); } /* * 没有网的情况也是出现了异常,然后就会调用到deliverError * */ @Override public void deliverError(VolleyError error) { if(error instanceof NoConnectionError) { Cache.Entry entry = this.getCacheEntry(); if (entry != null) { Response<JSONObject> response = parseNetworkResponse(new NetworkResponse(entry.data, entry.responseHeaders)); deliverResponse(response.result); return ; } } super.deliverError(error); } }这样都能很好的在没有网的情况下使用。
Http缓存机制的概念
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories