Android Volley完全解析4:带你从源码的角度理解Volley
原文鏈接:http://blog.csdn.net/guolin_blog/article/details/17656437,CSDN 郭霖
經(jīng)過(guò)前三篇文章的學(xué)習(xí),Volley的用法我們已經(jīng)掌握的差不多了,但是對(duì)于Volley的工作原理,恐怕有很多朋友還不是很清楚。因此,本篇文章中我們就來(lái)一起閱讀一下Volley的源碼,將它的工作流程整體地梳理一遍。同時(shí),這也是Volley系列的最后一篇文章了。
其實(shí),Volley的官方文檔中本身就附有了一張Volley的工作流程圖,如下圖所示。
多數(shù)朋友突然看到一張這樣的圖,應(yīng)該會(huì)和我一樣,感覺一頭霧水吧?沒錯(cuò),目前我們對(duì)Volley背后的工作原理還沒有一個(gè)概念性的理解,直接就來(lái)看這張圖自然會(huì)有些吃力。不過(guò)沒關(guān)系,下面我們就去分析一下Volley的源碼,之后再重新來(lái)看這張圖就會(huì)好理解多了。
說(shuō)起分析源碼,那么應(yīng)該從哪兒開始看起呢?這就要回顧一下Volley的用法了,還記得嗎,使用Volley的第一步,首先要調(diào)用Volley.newRequestQueue(context)方法來(lái)獲取一個(gè)RequestQueue對(duì)象,那么我們自然要從這個(gè)方法開始看起了,代碼如下所示:
public static RequestQueue newRequestQueue(Context context) { return newRequestQueue(context, null); }這個(gè)方法僅僅只有一行代碼,只是調(diào)用了
newRequestQueue()的方法重載,并給第二個(gè)參數(shù)傳入null。那我們看下帶有兩個(gè)參數(shù)的newRequestQueue()方法中的代碼,如下所示:
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的,則去創(chuàng)建一個(gè)HttpStack對(duì)象,這里會(huì)判斷如果手機(jī)系統(tǒng)版本號(hào)是大于9的,則創(chuàng)建一個(gè)HurlStack的實(shí)例,否則就創(chuàng)建一個(gè)HttpClientStack的實(shí)例。實(shí)際上
HurlStack的內(nèi)部就是使用HttpURLConnection進(jìn)行網(wǎng)絡(luò)通訊的,而HttpClientStack的內(nèi)部則是使用HttpClient進(jìn)行網(wǎng)絡(luò)通訊的,這里為什么這樣選擇呢?可以參考我之前翻譯的一篇文章Android訪問(wèn)網(wǎng)絡(luò),使用HttpURLConnection還是HttpClient?
創(chuàng)建好了HttpStack之后,接下來(lái)又創(chuàng)建了一個(gè)Network對(duì)象,它是用于根據(jù)傳入的HttpStack對(duì)象來(lái)處理網(wǎng)絡(luò)請(qǐng)求的,緊接著new出一個(gè)RequestQueue對(duì)象,并調(diào)用它的start()方法進(jìn)行啟動(dòng),然后將RequestQueue返回,這樣newRequestQueue()的方法就執(zhí)行結(jié)束了。
那么RequestQueue的start()方法內(nèi)部到底執(zhí)行了什么東西呢?我們跟進(jìn)去瞧一瞧:
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(); } }這里先是創(chuàng)建了一個(gè)CacheDispatcher的實(shí)例,然后調(diào)用了它的start()方法,接著在一個(gè)for循環(huán)里去創(chuàng)建NetworkDispatcher的實(shí)例,并分別調(diào)用它們的start()方法。這里的CacheDispatcher和NetworkDispatcher都是繼承自Thread的,而默認(rèn)情況下for循環(huán)會(huì)執(zhí)行四次,也就是說(shuō)當(dāng)調(diào)用了Volley.newRequestQueue(context)之后,就會(huì)有五個(gè)線程一直在后臺(tái)運(yùn)行,不斷等待網(wǎng)絡(luò)請(qǐng)求的到來(lái),
其中
CacheDispatcher是緩存線程,NetworkDispatcher是網(wǎng)絡(luò)請(qǐng)求線程。
得到了RequestQueue之后,我們只需要構(gòu)建出相應(yīng)的Request,然后調(diào)用RequestQueue的add()方法將Request傳入就可以完成網(wǎng)絡(luò)請(qǐng)求操作了,那么不用說(shuō),add()方法的內(nèi)部肯定有著非常復(fù)雜的邏輯,我們來(lái)一起看一下:
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行的時(shí)候會(huì)判斷當(dāng)前的請(qǐng)求是否可以緩存,如果不能緩存則在第12行直接將這條請(qǐng)求加入網(wǎng)絡(luò)請(qǐng)求隊(duì)列,可以緩存的話則在第33行將這條請(qǐng)求加入緩存隊(duì)列。在默認(rèn)情況下,每條請(qǐng)求都是可以緩存的,當(dāng)然我們也可以調(diào)用Request的setShouldCache(false)方法來(lái)改變這一默認(rèn)行為。
OK,那么既然默認(rèn)每條請(qǐng)求都是可以緩存的,自然就被添加到了緩存隊(duì)列中,于是一直在后臺(tái)等待的緩存線程就要開始運(yùn)行起來(lái)了,我們看下CacheDispatcher中的run()方法,代碼如下所示:
public class CacheDispatcher extends Thread { ……@Overridepublic 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; } } }代碼有點(diǎn)長(zhǎng),我們只挑重點(diǎn)看。首先在11行可以看到一個(gè)while(true)循環(huán),說(shuō)明緩存線程始終是在運(yùn)行的,接著在第23行會(huì)嘗試從緩存當(dāng)中取出響應(yīng)結(jié)果,如何為空的話則把這條請(qǐng)求加入到網(wǎng)絡(luò)請(qǐng)求隊(duì)列中,如果不為空的話再判斷該緩存是否已過(guò)期,如果已經(jīng)過(guò)期了則同樣把這條請(qǐng)求加入到網(wǎng)絡(luò)請(qǐng)求隊(duì)列中,否則就認(rèn)為不需要重發(fā)網(wǎng)絡(luò)請(qǐng)求,直接使用緩存中的數(shù)據(jù)即可。之后會(huì)在第39行調(diào)用Request的
parseNetworkResponse()方法來(lái)對(duì)數(shù)據(jù)進(jìn)行解析,再往后就是將解析出來(lái)的數(shù)據(jù)進(jìn)行回調(diào)了,這部分代碼我們先跳過(guò),因?yàn)樗倪壿嫼蚇etworkDispatcher后半部分的邏輯是基本相同的,那么我們等下合并在一起看就好了,先來(lái)看一下NetworkDispatcher中是怎么處理網(wǎng)絡(luò)請(qǐng)求隊(duì)列的,代碼如下所示:
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)循環(huán),說(shuō)明網(wǎng)絡(luò)請(qǐng)求線程也是在不斷運(yùn)行的。在第28行的時(shí)候會(huì)調(diào)用Network的performRequest()方法來(lái)去發(fā)送網(wǎng)絡(luò)請(qǐng)求,而Network是一個(gè)接口,這里具體的實(shí)現(xiàn)是BasicNetwork,我們來(lái)看下它的
performRequest()方法,如下所示:
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) { …… } } } }這段方法中大多都是一些網(wǎng)絡(luò)請(qǐng)求細(xì)節(jié)方面的東西,我們并不需要太多關(guān)心,需要注意的是在第14行調(diào)用了HttpStack的performRequest()方法,這里的HttpStack就是在一開始調(diào)用newRequestQueue()方法是創(chuàng)建的實(shí)例,默認(rèn)情況下如果系統(tǒng)版本號(hào)大于9就創(chuàng)建的HurlStack對(duì)象,否則創(chuàng)建HttpClientStack對(duì)象。前面已經(jīng)說(shuō)過(guò),這兩個(gè)對(duì)象的內(nèi)部實(shí)際就是分別使用HttpURLConnection和HttpClient來(lái)發(fā)送網(wǎng)絡(luò)請(qǐng)求的,我們就不再跟進(jìn)去閱讀了,之后會(huì)將服務(wù)器返回的數(shù)據(jù)組裝成一個(gè)NetworkResponse對(duì)象進(jìn)行返回。
在NetworkDispatcher中收到了NetworkResponse這個(gè)返回值后又會(huì)調(diào)用Request的parseNetworkResponse()方法來(lái)解析NetworkResponse中的數(shù)據(jù),以及將數(shù)據(jù)寫入到緩存,這個(gè)方法的實(shí)現(xiàn)是交給Request的子類來(lái)完成的,因?yàn)椴煌N類的Request解析的方式也肯定不同。還記得我們?cè)谏弦黄恼轮袑W(xué)習(xí)的自定義Request的方式嗎?其中parseNetworkResponse()這個(gè)方法就是必須要重寫的。
在解析完了NetworkResponse中的數(shù)據(jù)之后,又會(huì)調(diào)用ExecutorDelivery的postResponse()方法來(lái)回調(diào)解析出的數(shù)據(jù),代碼如下所示:
public void postResponse(Request<?> request, Response<?> response, Runnable runnable) { request.markDelivered(); request.addMarker("post-response"); mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, runnable)); }其中,在mResponsePoster的execute()方法中傳入了一個(gè)ResponseDeliveryRunnable對(duì)象,就可以保證該對(duì)象中的run()方法就是在主線程當(dāng)中運(yùn)行的了,我們看下run()方法中的代碼是什么樣的:
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(); } } }代碼雖然不多,但我們并不需要行行閱讀,抓住重點(diǎn)看即可。其中在第22行調(diào)用了Request的deliverResponse()方法,有沒有感覺很熟悉?沒錯(cuò),這個(gè)就是我們?cè)谧远xRequest時(shí)需要重寫的另外一個(gè)方法,每一條網(wǎng)絡(luò)請(qǐng)求的響應(yīng)都是回調(diào)到這個(gè)方法中,最后我們?cè)僭谶@個(gè)方法中將響應(yīng)的數(shù)據(jù)回調(diào)到Response.Listener的onResponse()方法中就可以了。
好了,到這里我們就把Volley的完整執(zhí)行流程全部梳理了一遍,你是不是已經(jīng)感覺已經(jīng)很清晰了呢?對(duì)了,還記得在文章一開始的那張流程圖嗎,剛才還不能理解,現(xiàn)在我們?cè)賮?lái)重新看下這張圖:
其中藍(lán)色部分代表主線程,綠色部分代表緩存線程,橙色部分代表網(wǎng)絡(luò)線程。我們?cè)谥骶€程中調(diào)用RequestQueue的add()方法來(lái)添加一條網(wǎng)絡(luò)請(qǐng)求,這條請(qǐng)求會(huì)先被加入到緩存隊(duì)列當(dāng)中,如果發(fā)現(xiàn)可以找到相應(yīng)的緩存結(jié)果就直接讀取緩存并解析,然后回調(diào)給主線程。如果在緩存中沒有找到結(jié)果,則將這條請(qǐng)求加入到網(wǎng)絡(luò)請(qǐng)求隊(duì)列中,然后處理發(fā)送HTTP請(qǐng)求,解析響應(yīng)結(jié)果,寫入緩存,并回調(diào)主線程。
怎么樣,是不是感覺現(xiàn)在理解這張圖已經(jīng)變得輕松簡(jiǎn)單了?好了,到此為止我們就把Volley的用法和源碼全部學(xué)習(xí)完了,相信你已經(jīng)對(duì)Volley非常熟悉并可以將它應(yīng)用到實(shí)際項(xiàng)目當(dāng)中了,那么Volley完全解析系列的文章到此結(jié)束,感謝大家有耐心看到最后。
總結(jié)
以上是生活随笔為你收集整理的Android Volley完全解析4:带你从源码的角度理解Volley的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Android Volley完全解析3:
- 下一篇: Android OkHttp完全解析