轉載請註明出處:http://blog.csdn.net/guolin_blog/article/details/17656437java
通過前三篇文章的學習,Volley的用法咱們已經掌握的差很少了,可是對於Volley的工做原理,恐怕有不少朋友還不是很清楚。所以,本篇文章中咱們就來一塊兒閱讀一下Volley的源碼,將它的工做流程總體地梳理一遍。同時,這也是Volley系列的最後一篇文章了。緩存
其實,Volley的官方文檔中自己就附有了一張Volley的工做流程圖,以下圖所示。服務器
多數朋友忽然看到一張這樣的圖,應該會和我同樣,感受一頭霧水吧?沒錯,目前咱們對Volley背後的工做原理尚未一個概念性的理解,直接就來看這張圖天然會有些吃力。不過不要緊,下面咱們就去分析一下Volley的源碼,以後再從新來看這張圖就會好理解多了。網絡
提及分析源碼,那麼應該從哪兒開始看起呢?這就要回顧一下Volley的用法了,還記得嗎,使用Volley的第一步,首先要調用Volley.newRequestQueue(context)方法來獲取一個RequestQueue對象,那麼咱們天然要從這個方法開始看起了,代碼以下所示:app
[java] view plain copyide
- public static RequestQueue newRequestQueue(Context context) {
- return newRequestQueue(context, null);
- }
這個方法僅僅只有一行代碼,只是調用了newRequestQueue()的方法重載,並給第二個參數傳入null。那咱們看下帶有兩個參數的newRequestQueue()方法中的代碼,以下所示:post
[java] view plain copy學習
- 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 {
- stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
- }
- }
- Network network = new BasicNetwork(stack);
- RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
- queue.start();
- return queue;
- }
能夠看到,這裏在第10行判斷若是stack是等於null的,則去建立一個HttpStack對象,這裏會判斷若是手機系統版本號是大於9的,則建立一個HurlStack的實例,不然就建立一個HttpClientStack的實例。實際上HurlStack的內部就是使用HttpURLConnection進行網絡通信的,而HttpClientStack的內部則是使用HttpClient進行網絡通信的,這裏爲何這樣選擇呢?能夠參考我以前翻譯的一篇文章Android訪問網絡,使用HttpURLConnection仍是HttpClient?ui
建立好了HttpStack以後,接下來又建立了一個Network對象,它是用於根據傳入的HttpStack對象來處理網絡請求的,緊接着new出一個RequestQueue對象,並調用它的start()方法進行啓動,而後將RequestQueue返回,這樣newRequestQueue()的方法就執行結束了。this
那麼RequestQueue的start()方法內部到底執行了什麼東西呢?咱們跟進去瞧一瞧:
[java] view plain copy
- 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 NetworkDispatcher(mNetworkQueue, mNetwork,
- mCache, mDelivery);
- mDispatchers[i] = networkDispatcher;
- networkDispatcher.start();
- }
- }
這裏先是建立了一個CacheDispatcher的實例,而後調用了它的start()方法,接着在一個for循環裏去建立NetworkDispatcher的實例,並分別調用它們的start()方法。這裏的CacheDispatcher和NetworkDispatcher都是繼承自Thread的,而默認狀況下for循環會執行四次,也就是說當調用了Volley.newRequestQueue(context)以後,就會有五個線程一直在後臺運行,不斷等待網絡請求的到來,其中CacheDispatcher是緩存線程,NetworkDispatcher是網絡請求線程。
獲得了RequestQueue以後,咱們只須要構建出相應的Request,而後調用RequestQueue的add()方法將Request傳入就能夠完成網絡請求操做了,那麼不用說,add()方法的內部確定有着很是複雜的邏輯,咱們來一塊兒看一下:
[java] view plain copy
- public <T> Request<T> add(Request<T> request) {
- // Tag the request as belonging to this queue and add it to the set of current requests.
- request.setRequestQueue(this);
- synchronized (mCurrentRequests) {
- mCurrentRequests.add(request);
- }
- // Process requests in the order they are added.
- request.setSequence(getSequenceNumber());
- request.addMarker("add-to-queue");
- // If the request is uncacheable, skip the cache queue and go straight to the network.
- if (!request.shouldCache()) {
- mNetworkQueue.add(request);
- return request;
- }
- // Insert request into stage if there's already a request with the same cache key in flight.
- 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 {
- // Insert 'null' queue for this cacheKey, indicating there is now a request in
- // flight.
- mWaitingRequests.put(cacheKey, null);
- mCacheQueue.add(request);
- }
- return request;
- }
- }
能夠看到,在第11行的時候會判斷當前的請求是否能夠緩存,若是不能緩存則在第12行直接將這條請求加入網絡請求隊列,能夠緩存的話則在第33行將這條請求加入緩存隊列。在默認狀況下,每條請求都是能夠緩存的,固然咱們也能夠調用Request的setShouldCache(false)方法來改變這一默認行爲。
OK,那麼既然默認每條請求都是能夠緩存的,天然就被添加到了緩存隊列中,因而一直在後臺等待的緩存線程就要開始運行起來了,咱們看下CacheDispatcher中的run()方法,代碼以下所示:
[java] view plain copy
- public class CacheDispatcher extends Thread {
-
- ……
-
- @Override
- public void run() {
- if (DEBUG) VolleyLog.v("start new dispatcher");
- Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
- // Make a blocking call to initialize the cache.
- 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;
- }
- }
- }
- }
代碼有點長,咱們只挑重點看。首先在11行能夠看到一個while(true)循環,說明緩存線程始終是在運行的,接着在第23行會嘗試從緩存當中取出響應結果,如何爲空的話則把這條請求加入到網絡請求隊列中,若是不爲空的話再判斷該緩存是否已過時,若是已通過期了則一樣把這條請求加入到網絡請求隊列中,不然就認爲不須要重發網絡請求,直接使用緩存中的數據便可。以後會在第39行調用Request的parseNetworkResponse()方法來對數據進行解析,再日後就是將解析出來的數據進行回調了,這部分代碼咱們先跳過,由於它的邏輯和NetworkDispatcher後半部分的邏輯是基本相同的,那麼咱們等下合併在一塊兒看就行了,先來看一下NetworkDispatcher中是怎麼處理網絡請求隊列的,代碼以下所示:
[java] view plain copy
- public class NetworkDispatcher extends Thread {
- ……
- @Override
- 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;
- }
- addTrafficStatsTag(request);
- // 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));
- }
- }
- }
- }
一樣地,在第7行咱們看到了相似的while(true)循環,說明網絡請求線程也是在不斷運行的。在第28行的時候會調用Network的performRequest()方法來去發送網絡請求,而Network是一個接口,這裏具體的實現是BasicNetwork,咱們來看下它的performRequest()方法,以下所示:
[java] view plain copy
- public class BasicNetwork implements Network {
- ……
- @Override
- 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() == null ? null : request.getCacheEntry().data,
- responseHeaders, true);
- }
- // Some responses such as 204s do not have content. We must check.
- if (httpResponse.getEntity() != null) {
- responseContents = entityToBytes(httpResponse.getEntity());
- } else {
- // Add 0 byte response as a way of honestly representing a
- // no-content request.
- responseContents = new byte[0];
- }
- // if the request is slow, log it.
- long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
- logSlowRequests(requestLifetime, request, responseContents, statusLine);
- if (statusCode < 200 || statusCode > 299) {
- throw new IOException();
- }
- return new NetworkResponse(statusCode, responseContents, responseHeaders, false);
- } catch (Exception e) {
- ……
- }
- }
- }
- }
這段方法中大多都是一些網絡請求細節方面的東西,咱們並不須要太多關心,須要注意的是在第14行調用了HttpStack的performRequest()方法,這裏的HttpStack就是在一開始調用newRequestQueue()方法是建立的實例,默認狀況下若是系統版本號大於9就建立的HurlStack對象,不然建立HttpClientStack對象。前面已經說過,這兩個對象的內部實際就是分別使用HttpURLConnection和HttpClient來發送網絡請求的,咱們就再也不跟進去閱讀了,以後會將服務器返回的數據組裝成一個NetworkResponse對象進行返回。
在NetworkDispatcher中收到了NetworkResponse這個返回值後又會調用Request的parseNetworkResponse()方法來解析NetworkResponse中的數據,以及將數據寫入到緩存,這個方法的實現是交給Request的子類來完成的,由於不一樣種類的Request解析的方式也確定不一樣。還記得咱們在上一篇文章中學習的自定義Request的方式嗎?其中parseNetworkResponse()這個方法就是必需要重寫的。
在解析完了NetworkResponse中的數據以後,又會調用ExecutorDelivery的postResponse()方法來回調解析出的數據,代碼以下所示:
[java] view plain copy
- public void postResponse(Request<?> request, Response<?> response, Runnable runnable) {
- request.markDelivered();
- request.addMarker("post-response");
- mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, runnable));
- }
其中,在mResponsePoster的execute()方法中傳入了一個ResponseDeliveryRunnable對象,就能夠保證該對象中的run()方法就是在主線程當中運行的了,咱們看下run()方法中的代碼是什麼樣的:
[java] view plain copy
- private class ResponseDeliveryRunnable implements Runnable {
- private final Request mRequest;
- private final Response mResponse;
- private final Runnable mRunnable;
-
- public ResponseDeliveryRunnable(Request request, Response response, Runnable runnable) {
- mRequest = request;
- mResponse = response;
- mRunnable = runnable;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- 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();
- }
- }
- }
代碼雖然很少,但咱們並不須要行行閱讀,抓住重點看便可。其中在第22行調用了Request的deliverResponse()方法,有沒有感受很熟悉?沒錯,這個就是咱們在自定義Request時須要重寫的另一個方法,每一條網絡請求的響應都是回調到這個方法中,最後咱們再在這個方法中將響應的數據回調到Response.Listener的onResponse()方法中就能夠了。
好了,到這裏咱們就把Volley的完整執行流程所有梳理了一遍,你是否是已經感受已經很清晰了呢?對了,還記得在文章一開始的那張流程圖嗎,剛纔還不能理解,如今咱們再來從新看下這張圖:
其中藍色部分表明主線程,綠色部分表明緩存線程,橙色部分表明網絡線程。咱們在主線程中調用RequestQueue的add()方法來添加一條網絡請求,這條請求會先被加入到緩存隊列當中,若是發現能夠找到相應的緩存結果就直接讀取緩存並解析,而後回調給主線程。若是在緩存中沒有找到結果,則將這條請求加入到網絡請求隊列中,而後處理髮送HTTP請求,解析響應結果,寫入緩存,並回調主線程。
怎麼樣,是否是感受如今理解這張圖已經變得輕鬆簡單了?好了,到此爲止咱們就把Volley的用法和源碼所有學習完了,相信你已經對Volley很是熟悉並能夠將它應用到實際項目當中了,那麼Volley徹底解析系列的文章到此結束,感謝你們有耐心看到最後。