Android working with Volley 详解(3)

<1>.RequestQueue默认会把数据缓存到本地,比如一张图片,一些相关方法参考DiskBasedCache类;但有时我们不需要对数据进行缓存,只需要在添加请求的时候通过Request.setShouldCache(false)即可;

<2>.查看缓存:

RequestQueue reqQueue = ...;
Cache cache = reqQueue.getCache(); Entry entry = cache.get(url); if(entry != null){ try { String data = new String(entry.data, "UTF-8"); // handle data, like converting it to xml, json, bitmap etc., } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }else{ // Cached response doesn't exists. Make network call here }

Cache还提供了其它相关的方法,比如remove{删除},invalidate{不会删除缓存的数据,而是使其失效,当网络请求成功获取到新数据时,会覆盖掉之前的数据},clear{清空};

除了使用Cache.clear()方法清空缓存,还有另外一种方法来请空缓存:

protected void clearCache() { ClearCacheRequest ccr = new ClearCacheRequest(reqQueue.getCache(), new Runnable() { @Override public void run() { } }); ccr.setTag(this); reqQueue.add(ccr); }

八、取消请求

有时候,我们可能需要手动取消请求,比如,在一个请求还未完成时,程序即出了,如果再继续请求没有太大的意义,还有可能造成程序崩溃,通常这种情况我们在onStop方法中取消请求,下面就来看看如何取消请求;

RequestQueue reqQueue ...;
reqQueue.cancelAll(this); // reqQueue.cancelAll(new RequestFilter() { // @Override // public boolean apply(Request<?> request) { // return false; // } // });

九、自定义Request

先来看StringRequest的源码实现

public class StringRequest extends Request<String> { private final Listener<String> mListener; /** * Creates a new request with the given method. * * @param method the request {@link Method} to use * @param url URL to fetch the string at * @param listener Listener to receive the String response * @param errorListener Error listener, or null to ignore errors */ public StringRequest(int method, String url, Listener<String> listener, ErrorListener errorListener) { super(method, url, errorListener); mListener = listener; } /** * Creates a new GET request. * * @param url URL to fetch the string at * @param listener Listener to receive the String response * @param errorListener Error listener, or null to ignore errors */ public StringRequest(String url, Listener<String> listener, ErrorListener errorListener) { this(Method.GET, url, listener, errorListener); } @Override protected void deliverResponse(String response) { mListener.onResponse(response); } @Override protected Response<String> parseNetworkResponse(NetworkResponse response) { String parsed; try { parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); } catch (UnsupportedEncodingException e) { parsed = new String(response.data); } return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); } }

通过上面StringRequest的源码,相信实现一个自定义Request对大家来说都没有太大的难度,也就是重写两个方法,deliverResponse(仅仅一行代码,有什么难的?)和parseNetworkResponse,主要就是实现parseNetworkResponse,下面参照StringRequest来实现一个XmlRequest;

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/d4623144501e955441416731ce045e89.html