要说源码分析,我们得先看一下官方的配图:
从图中,我们还可以看到 volley 的工作其实就是三个线程之间的数据传递 主线程 缓存线程 网络线程。
既然是源码分析,当然是得从源码开始啦(怎么下载源码我就不说了!不会的自行谷歌)!那我们从哪段源码开始嘞?我们就从我们使用 volley 框架的第一句代码开始。
Volley.newRequestQueue(context) 是我们使用 volley 框架的第一句代码!这句代码是用创建个 RequestQueue (请求队列。对,这个就是 volley 工作流程中的第一步的铺垫。这样请求才能有容器装啊!)。那好,我们现在就来看一下 newRequestQueue(context) 这个静态方法:
public static RequestQueue newRequestQueue(Context context) { return newRequestQueue(context, null); } public static RequestQueue newRequestQueue(Context context, HttpStack stack) { File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR); String userAgent = "volley/0"; try { String packageName = context.getPackageName(); PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); userAgent = packageName + "/" + info.versionCode; } catch (NameNotFoundException e) { } if (stack == null) { if (Build.VERSION.SDK_INT >= 9) { stack = new HurlStack(); } else { // Prior to Gingerbread, HttpUrlConnection was unreliable. // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent)); } } Network network = new BasicNetwork(stack); RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network); queue.start(); return queue; }
从代码中可以看出,我们使用的是 newRequestQueue(Context context, HttpStack stack) 这个函数的重载方法!我简要对这个方法说明下:在系统版本大于等于 9 的时候,我们创建 HurlStack(就是 HttpUrlConnection),在小于 9 的时候我们创建 HttpClientStack(就是 HttpClient) 至于为啥要要这么做。那就是 HttpUrlConnection 的性能要比HttpClient 的好。当然这里我还可以使用另外第三发的 HTTP 库 。比如说 okhttp 。这里我们只要调用 newRequestQueue(Context context, HttpStack stack) 这个方法就行了!当然 要对 okhttp 做简单的封装了!前提是要继承 HttpStack 这个接口啊!
接下来 我们直接看这句代码:RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network); 这就是我们要创建的请求队列啦!看 RequestQueue 这个类:
我们先看构造函数(直接看最复杂的!哈哈)
public RequestQueue(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery) { mCache = cache; mNetwork = network; mDispatchers = new NetworkDispatcher[threadPoolSize]; mDelivery = delivery; }
可以看到,需要传入 缓存 ,网络执行器,线程池大小,返回结果分发器。这四个参数!接着 我们再来看一下 queue.start() 这句代码的含义!还是一样先看代码:
public void start() { stop(); // Make sure any currently running dispatchers are stopped. // Create the cache dispatcher and start it. mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery); mCacheDispatcher.start(); // Create network dispatchers (and corresponding threads) up to the pool size. for (int i = 0; i < mDispatchers.length; i++) { NetworkDispatcher networkDispatcher = new (mNetworkQueue, mNetwork, mCache, mDelivery); mDispatchers[i] = networkDispatcher; networkDispatcher.start(); } }
先来解释下这这段代码:先停止当前正在运行的所有的线程!接着 初始化 CacheDispatcher(缓存调度器) 并启动他!接着就是启动 NetworkDispatcher(网络调度器) 这有多个。他的个数全靠 threadPoolSize 这个变量控制(默认大小是4)。这样一来。请求队列就是初始化好了!就等待任务加入了啦!!那我们就趁热打铁,直接看加入任务队列的源码:
public Request { request.setRequestQueue(this); synchronized (mCurrentRequests) { mCurrentRequests.add(request); } request.setSequence(getSequenceNumber()); request.addMarker("add-to-queue"); if (!request.shouldCache()) { mNetworkQueue.add(request); return request; } synchronized (mWaitingRequests) { String cacheKey = request.getCacheKey(); if (mWaitingRequests.containsKey(cacheKey)) { // There is already a request in flight. Queue up. Queue<Request> stagedRequests = mWaitingRequests.get(cacheKey); if (stagedRequests == null) { stagedRequests = new LinkedList<Request>(); } stagedRequests.add(request); mWaitingRequests.put(cacheKey, stagedRequests); if (VolleyLog.DEBUG) { VolleyLog.v("Request for cacheKey=%s is in flight, putting on hold.", cacheKey); } } else { mWaitingRequests.put(cacheKey, null); mCacheQueue.add(request); } return request; } }
依旧是来解读这段代码,在解读这该段代码的时候,我们先来弄清楚其中三个变量的含义:
//当前 RequestQueue 中所有的请求队列 private final Set<Request> mCurrentRequests = new HashSet<Request>(); //缓存队列 private final PriorityBlockingQueue<Request> mCacheQueue = new PriorityBlockingQueue<Request>(); //网络队列 正在进入的 private final PriorityBlockingQueue<Request> mNetworkQueue = new PriorityBlockingQueue<Request>();
含义如注释!那么我们接着看 add(Request request) 这个方法!首先还是先把任务加入 当前队列。之后request.shouldCache() 判断该任务需要被缓存。不需要的话 直接进入 网络队列!否则的话就加入缓存队列!!
分析完了怎么加入队列之后,我们要来分析下两外两个类了 CacheDispatcher 和 NetworkDispatcher 这里先说下这两个类的共同点:那就是都继承了 Thread 类!也就说他们都是线程类!可以被执行。这也就解释了 RequestQueue 类中的start() 方法中 mCacheDispatcher.start() 和 networkDispatcher.start() 这两句代码!
那么我们先来看一下 CacheDispatcher 这个类!我们直接该类最核心的方法 run() 方法!
public void run() { if (DEBUG) VolleyLog.v("start new dispatcher"); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); mCache.initialize(); while (true) { try { // Get a request from the cache triage queue, blocking until // at least one is available. final Request request = mCacheQueue.take(); request.addMarker("cache-queue-take"); // If the request has been canceled, don't bother dispatching it. if (request.isCanceled()) { request.finish("cache-discard-canceled"); continue; } // Attempt to retrieve this item from cache. 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 it is completely expired, just send it to the network. if (entry.isExpired()) { request.addMarker("cache-hit-expired"); request.setCacheEntry(entry); mNetworkQueue.put(request); continue; } // We have a cache hit; parse its data for delivery back to the request. request.addMarker("cache-hit"); Response<?> response = request.parseNetworkResponse( new NetworkResponse(entry.data, entry.responseHeaders)); request.addMarker("cache-hit-parsed"); if (!entry.refreshNeeded()) { // Completely unexpired cache hit. Just deliver the response. mDelivery.postResponse(request, response); } else { // Soft-expired cache hit. We can deliver the cached response, // but we need to also send the request to the network for // refreshing. request.addMarker("cache-hit-refresh-needed"); request.setCacheEntry(entry); // Mark the response as intermediate. response.intermediate = true; // Post the intermediate response back to the user and have // the delivery then forward the request along to the network. mDelivery.postResponse(request, response, new Runnable() { @Override public void run() { try { mNetworkQueue.put(request); } catch (InterruptedException e) { // Not much we can do about this. } } }); } } catch (InterruptedException e) { // We may have been interrupted because it was time to quit. if (mQuit) { return; } continue; } } }
这段代码中有句代码非常抢眼,没错!那就是 while(true) 这句话了!有的童鞋可能已经想到了:这是个死循环(这不废话!),另外肯定是在不同的从某个队列中取/存数据。没错,就是这样啊!其实很简单!我们接着细说:首先从缓存队列中去除队列,接着判断该请求是否已经取消 if (request.isCanceled()) 如果已经取消的话,就是不走下面的代码!继续从头循环!反之,从缓存中读取数据,如果没有的话就把该队列加入网络请求队列。如果有的但是缓存已经过期的话 也是加入网络请求队列( if (entry == null) 和 if (entry.isExpired()) 这两个 if 下的语句就是处理上面两个功能的)。如果以上两个条件都不满足的话!就直接 request.parseNetworkResponse(new NetworkResponse(entry.data, entry.responseHeaders)) 解析缓存中的数据进行回调了!
下面我们看 NetworkDispatcher 类的代码,同样的我们直接看 核心代码:
public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); Request request; while (true) { try { // Take a request from the queue. request = mQueue.take(); } catch (InterruptedException e) { // We may have been interrupted because it was time to quit. if (mQuit) { return; } continue; } try { request.addMarker("network-queue-take"); // If the request was cancelled already, do not perform the // network request. if (request.isCanceled()) { request.finish("network-discard-cancelled"); continue; } // Tag the request (if API >= 14) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { TrafficStats.setThreadStatsTag(request.getTrafficStatsTag()); } // Perform the network request. NetworkResponse networkResponse = mNetwork.performRequest(request); request.addMarker("network-http-complete"); // If the server returned 304 AND we delivered a response already, // we're done -- don't deliver a second identical response. if (networkResponse.notModified && request.hasHadResponseDelivered()) { request.finish("not-modified"); continue; } // Parse the response here on the worker thread. Response<?> response = request.parseNetworkResponse(networkResponse); request.addMarker("network-parse-complete"); // Write to cache if applicable. // TODO: Only update cache metadata instead of entire record for 304s. if (request.shouldCache() && response.cacheEntry != null) { mCache.put(request.getCacheKey(), response.cacheEntry); request.addMarker("network-cache-written"); } // Post the response back. request.markDelivered(); mDelivery.postResponse(request, response); } catch (VolleyError volleyError) { parseAndDeliverNetworkError(request, volleyError); } catch (Exception e) { VolleyLog.e(e, "Unhandled exception %s", e.toString()); mDelivery.postError(request, new VolleyError(e)); } } }
同样的是,先从网络请求队列中取出任务,接着在判断是否要取消,如果要则跳过下面的代码,重新取任务!调用 NetworkResponse networkResponse = mNetwork.performRequest(request); 这句代码,获取 网络返回结果!接着,代码和 CacheDispatcher 中差不多!唯一的区别就是:如果当前的请求需要加入缓存,则加入缓存!细心的同学可能发现了,CacheDispatcher 和 NetworkDispatcher 这两个类中有句相同的代码 Response<?> response = request.parseNetworkResponse(networkResponse); 就是这句!核心的就是parseNetworkResponse(networkResponse) 这个函数的实现我在上一篇 Volley 的使用以及自定义Request 中已经说过了!是有我们实现的!
这里的我们还得在注意一个类:那就是 BasicNetwork !其实这个类没有什么可以细说的!他就是请求网络接着返回结果!我这里也把核心代码上一下:
public NetworkResponse performRequest(Request<?> request) throws VolleyError { long requestStart = SystemClock.elapsedRealtime(); while (true) { HttpResponse httpResponse = null; byte[] responseContents = null; Map<String, String> responseHeaders = new HashMap<String, String>(); try { // Gather headers. Map<String, String> headers = new HashMap<String, String>(); addCacheHeaders(headers, request.getCacheEntry()); httpResponse = mHttpStack.performRequest(request, headers); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); responseHeaders = convertHeaders(httpResponse.getAllHeaders()); // Handle cache validation. if (statusCode == HttpStatus.SC_NOT_MODIFIED) { return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, request.getCacheEntry().data, responseHeaders, true); } responseContents = entityToBytes(httpResponse.getEntity()); // if the request is slow, log it. long requestLifetime = SystemClock.elapsedRealtime() - requestStart; logSlowRequests(requestLifetime, request, responseContents, statusLine); if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_NO_CONTENT) { throw new IOException(); } return new NetworkResponse(statusCode, responseContents, responseHeaders, false); } catch (SocketTimeoutException e) { attemptRetryOnException("socket", request, new TimeoutError()); } catch (ConnectTimeoutException e) { attemptRetryOnException("connection", request, new TimeoutError()); } catch (MalformedURLException e) { throw new RuntimeException("Bad URL " + request.getUrl(), e); } catch (IOException e) { int statusCode = 0; NetworkResponse networkResponse = null; if (httpResponse != null) { statusCode = httpResponse.getStatusLine().getStatusCode(); } else { throw new NoConnectionError(e); } VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl()); if (responseContents != null) { networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false); if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) { attemptRetryOnException("auth", request, new AuthFailureError(networkResponse)); } else { // TODO: Only throw ServerError for 5xx status codes. throw new ServerError(networkResponse); } } else { throw new NetworkError(networkResponse); } } } }
这个类 我就真的不细讲啦!!
上面已经说了,在解析玩数据之后其实就分发数据了!让用户能够在 UI线程中调用了!现在我们就来看一下这个分发类:ExecutorDelivery。 我们还是先看这个类的构造函数:
public (final Handler handler) { // Make an Executor that just wraps the handler. mResponsePoster = new Executor() { @Override public void execute(Runnable command) { handler.post(command); } }; }
从代码中我们可以看到,我们需要传一个Handller进入,此时我们在回想一下这个类在 RequestQueue 类中是怎么初始化的?
public RequestQueue(Cache cache, Network network, int threadPoolSize) { this(cache, network, threadPoolSize, new ExecutorDelivery(new Handler(Looper.getMainLooper()))); }
没错!大家可以看到,是传入了一个主线中的handler!
当在 CacheDispatcher 和 NetworkDispatcher 这两个类中调用了 mDelivery.postResponse(request, response); 这个方法的时,我们来看一下 ExecutorDelivery 这个类都做了什么!
public void postResponse(Request<?> request, Response<?> response, Runnable runnable) { request.markDelivered(); request.addMarker("post-response"); mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, runnable)); }
我们直接执行了了个Runnable-->ResponseDeliveryRunnable。那他又做了什么呢?
public void run() { // If this request has canceled, finish it and don't deliver. if (mRequest.isCanceled()) { mRequest.finish("canceled-at-delivery"); return; } // Deliver a normal response or error, depending. if (mResponse.isSuccess()) { mRequest.deliverResponse(mResponse.result); } else { mRequest.deliverError(mResponse.error); } // If this is an intermediate response, add a marker, otherwise we're done // and the request can be finished. if (mResponse.intermediate) { mRequest.addMarker("intermediate-response"); } else { mRequest.finish("done"); } // If we have been provided a post-delivery runnable, run it. if (mRunnable != null) { mRunnable.run(); } }
我们看最直接的这句代码 mRequest.deliverResponse(mResponse.result); 我们调用了 Request的中的一个方法(这个方法,依然是要我们自己实现!)。接着,我们在看 ExecutorDelivery 的构造函数时,我们就会豁然开朗!数据终于到了 UI线程了!
至此 volley 框架的整体流程分析完毕!!!!
还在说几句:volley 框架的架构设计非常优美!扩展性极高!这个大概得益于 volley 面向接口的设计方案吧!面向接口的架构设计 也是我不断努力的方向!!!!