日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

Android Volley完全解析4:带你从源码的角度理解Volley

發布時間:2025/4/16 Android 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android Volley完全解析4:带你从源码的角度理解Volley 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

原文鏈接:http://blog.csdn.net/guolin_blog/article/details/17656437,CSDN 郭霖

經過前三篇文章的學習,Volley的用法我們已經掌握的差不多了,但是對于Volley的工作原理,恐怕有很多朋友還不是很清楚。因此,本篇文章中我們就來一起閱讀一下Volley的源碼,將它的工作流程整體地梳理一遍。同時,這也是Volley系列的最后一篇文章了。

其實,Volley的官方文檔中本身就附有了一張Volley的工作流程圖,如下圖所示。

多數朋友突然看到一張這樣的圖,應該會和我一樣,感覺一頭霧水吧?沒錯,目前我們對Volley背后的工作原理還沒有一個概念性的理解,直接就來看這張圖自然會有些吃力。不過沒關系,下面我們就去分析一下Volley的源碼,之后再重新來看這張圖就會好理解多了。

說起分析源碼,那么應該從哪兒開始看起呢?這就要回顧一下Volley的用法了,還記得嗎,使用Volley的第一步,首先要調用Volley.newRequestQueue(context)方法來獲取一個RequestQueue對象,那么我們自然要從這個方法開始看起了,代碼如下所示:

public static RequestQueue newRequestQueue(Context context) { return newRequestQueue(context, null); }

這個方法僅僅只有一行代碼,只是調用了

newRequestQueue()的方法重載,并給第二個參數傳入null。那我們看下帶有兩個參數的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的,則去創建一個HttpStack對象,這里會判斷如果手機系統版本號是大于9的,則創建一個HurlStack的實例,否則就創建一個HttpClientStack的實例。實際上

HurlStack的內部就是使用HttpURLConnection進行網絡通訊的,而HttpClientStack的內部則是使用HttpClient進行網絡通訊的,這里為什么這樣選擇呢?可以參考我之前翻譯的一篇文章Android訪問網絡,使用HttpURLConnection還是HttpClient?

創建好了HttpStack之后,接下來又創建了一個Network對象,它是用于根據傳入的HttpStack對象來處理網絡請求的,緊接著new出一個RequestQueue對象,并調用它的start()方法進行啟動,然后將RequestQueue返回,這樣newRequestQueue()的方法就執行結束了。

那么RequestQueue的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 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()方法的內部肯定有著非常復雜的邏輯,我們來一起看一下:

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()方法,代碼如下所示:

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; } } }

代碼有點長,我們只挑重點看。首先在11行可以看到一個while(true)循環,說明緩存線程始終是在運行的,接著在第23行會嘗試從緩存當中取出響應結果,如何為空的話則把這條請求加入到網絡請求隊列中,如果不為空的話再判斷該緩存是否已過期,如果已經過期了則同樣把這條請求加入到網絡請求隊列中,否則就認為不需要重發網絡請求,直接使用緩存中的數據即可。之后會在第39行調用Request的

parseNetworkResponse()方法來對數據進行解析,再往后就是將解析出來的數據進行回調了,這部分代碼我們先跳過,因為它的邏輯和NetworkDispatcher后半部分的邏輯是基本相同的,那么我們等下合并在一起看就好了,先來看一下NetworkDispatcher中是怎么處理網絡請求隊列的,代碼如下所示:

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()方法,如下所示:

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()方法來回調解析出的數據,代碼如下所示:

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()方法中的代碼是什么樣的:

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完全解析系列的文章到此結束,感謝大家有耐心看到最后。

總結

以上是生活随笔為你收集整理的Android Volley完全解析4:带你从源码的角度理解Volley的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 中文字幕人妻一区二区三区在线视频 | 少妇2做爰hd韩国电影 | 国产在线看 | 向着小小的花蕾绽放 | 成人国产一区二区 | 美女黄18以下禁止观看 | www.中文字幕在线观看 | 人体av | 91久久超碰 | 大学生高潮无套内谢视频 | 成人福利视频网站 | www.一区二区三区四区 | 午夜激情av | 97在线观视频免费观看 | 少妇性l交大片免潘金莲 | 日本wwwwwww| 邻居少妇张开腿让我爽了在线观看 | 日韩av大片| 6680新视觉电影免费观看 | 91香蕉视频在线看 | 欧美极品视频在线观看 | 农村妇女毛片精品久久久 | 日韩激情视频网站 | 精品人妻av一区二区三区 | 青青草av在线播放 | 玖玖色在线 | 国产精品美女久久久久 | 亚洲女人天堂色在线7777 | 伊人超碰在线 | 中文字幕无码毛片免费看 | 色呦呦国产 | 免费毛片一区二区三区 | 日韩成人在线网站 | 日韩三级麻豆 | 男女洗澡互摸私密部位视频 | 狠狠干少妇 | 欧美激情动态图 | 日本电影成人 | 国产嫩草影院久久久久 | 一二三区视频 | 日韩在线视频网站 | 成人性毛片| 成人开心网 | 萌白酱一区二区 | 午夜精品在线 | 狂躁美女大bbbbbb黑人 | 日韩中文一区二区 | 婷婷天堂| 亚洲不卡在线视频 | 男人都懂的网址 | 中文字幕一区二 | 91久久超碰 | 欧美天堂在线 | 成年人爱爱视频 | 久艹在线视频 | 台湾一级视频 | 欧美在线色图 | www.在线国产 | 国产精品极品白嫩在线 | 天天燥日日燥 | 免费在线网站 | 青青草成人在线 | 久久大尺度| 久久xxxx| 嫩草影院在线观看视频 | 曰本女人与公拘交酡 | 日韩免费成人 | 日韩一卡二卡三卡 | 成年人免费av| 91亚洲精华国产精华精华液 | 久热国产视频 | 天天操天天操天天操天天 | 亚洲精品国产精品乱码在线观看 | 中文字幕一区二区不卡 | 亚洲经典一区二区三区 | 日韩美女少妇 | 3p在线视频 | 日韩电影在线观看中文字幕 | 91中文字幕网 | 性色视频 | 国产欧美一区二区三区精华液好吗 | 69堂在线观看 | 亚洲性生活片 | 久久久久极品 | 久久97精品 | 韩国理论午夜 | 午夜激情免费视频 | 国产亚洲欧美一区二区 | 欧美精品成人一区二区在线观看 | 色哟哟一区二区 | 亚洲美女精品视频 | 99久久久无码国产精品 | 欧洲午夜精品 | 鲁一鲁在线 | 久久久久久免费 | 天天干天天操av | 免费在线 | 精品日韩一区二区 | 国产99自拍 |