編輯:關於 Android 程式設計
Volley 是一個 HTTP 庫,能讓 Android App 更輕鬆地完成網路操作,而它最大的賣點是快且有效率。原始碼可以直接從 AOSP 倉庫取得,主要優點包括:
Volley 擅長的是那種為了顯示 UI 而發出的 RPC 型操作,例如抓回搜尋結果;回傳內容可以是原始字串、圖片或 JSON,格式相當自由。它把常用的樣板程式都包好了,讓我們能把注意力放回 App 本身的邏輯。
反過來說,Volley 並不適合下載大型檔案——因為它會把整個回應都保留在記憶體中進行解析。要下載大量資料,請改用 DownloadManager。
核心程式碼位於 AOSP 的 frameworks/volley,工具類別則放在 toolbox 底下。最簡單的整合方式是 clone 下來,設成 library project:
git clone https://android.googlesource.com/platform/frameworks/volley
接著以 Android library project 的形式匯入你的專案。以下就來逐段拆解它的 Java 原始碼。
用 Volley 的第一步是取得一個 RequestQueue,通常透過 Volley.newRequestQueue() 拿到預設實例。先看這個方法:
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: https://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) 只是轉呼重載版本並帶入 null。在重載方法裡,先用 context 取得快取目錄並組出 userAgent,接著判斷 stack 是否為 null——預設情況下確實是 null,所以會新建一個。系統版本 >= 9 時用 HurlStack(底層是 HttpUrlConnection),更舊的版本則退回 HttpClientStack(底層是 HttpClient),原因是 Gingerbread 之前的 HttpUrlConnection 並不可靠。有了 stack 之後包成 BasicNetwork,負責處理網路請求;最後才 new 出 RequestQueue,並傳入 DiskBasedCache(磁碟快取,目錄就是最前面取到的 cacheDir)與 network,再呼叫 start() 啟動。
在談 start() 之前,先看幾個關鍵成員與建構子:
//重復的請求將加入這個集合 private final Map<String, Queue<Request>> mWaitingRequests = new HashMap<String, Queue<Request>>(); //所有正在處理的請求任務的集合 private final Set<Request> mCurrentRequests = new HashSet<Request>(); //緩存任務的隊列 private final PriorityBlockingQueue<Request> mCacheQueue = new PriorityBlockingQueue<Request>(); //網絡請求隊列 private final PriorityBlockingQueue<Request> mNetworkQueue = new PriorityBlockingQueue<Request>(); //默認線程池大小 private static final int DEFAULT_NETWORK_THREAD_POOL_SIZE = 4; //用於響應數據的存儲與獲取 private final Cache mCache; //用於網絡請求 private final Network mNetwork; //用於分發響應數據 private final ResponseDelivery mDelivery; //網絡請求調度 private NetworkDispatcher[] mDispatchers; //緩存調度 private CacheDispatcher mCacheDispatcher; public RequestQueue(Cache cache, Network network) { this(cache, network, DEFAULT_NETWORK_THREAD_POOL_SIZE); } public RequestQueue(Cache cache, Network network, int threadPoolSize) { this(cache, network, threadPoolSize, new ExecutorDelivery(new Handler(Looper.getMainLooper()))); } public RequestQueue(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery) { mCache = cache; mNetwork = network; mDispatchers = new NetworkDispatcher[threadPoolSize]; mDelivery = delivery; } 三個建構子最終都會收到最後一個:mCache 與 mNetwork 就是 newRequestQueue 傳進來的 DiskBasedCache 與 BasicNetwork;mDispatchers 是網路調度器陣列,預設 4 個(DEFAULT_NETWORK_THREAD_POOL_SIZE);mDelivery 則是 new ExecutorDelivery(new Handler(Looper.getMainLooper())),專門負責把結果送回主執行緒。也就是說,RequestQueue 完全可以自行組裝,不必非用預設的 newRequestQueue 不可。
接著看 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(); } } 邏輯很單純:先 stop() 確保舊的調度器都收工,然後建立並啟動一個 CacheDispatcher,再建立並啟動四個 NetworkDispatcher。所謂「啟動佇列」,其實就是把任務交給這兩類調度器去跑。
那麼任務是怎麼進佇列的?就是 add():
public Request add(Request 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; } } 程式碼看起來長,但不難讀:先把請求登記進 mCurrentRequests,接著判斷要不要快取。若 shouldCache() 為 false,直接丟進 mNetworkQueue 結束;預設是快取的,於是走進 mWaitingRequests 的判斷,避免同一個 cacheKey 被重複送出——若已有相同的請求在飛行中,就排進等待佇列,否則佔位後送進 mCacheQueue。
start() 之後,請求就交由 CacheDispatcher 與 NetworkDispatcher 處理。兩者都繼承自 Thread,本質上是背景工作執行緒,一個負責從快取取資料,一個負責發網路請求。
它不停地從 mCacheQueue 撈任務,run() 如下:
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; } } } 流程是:先 mCache.initialize() 初始化快取,然後進入無窮迴圈。取出任務後,若已取消就 finish 並重新迴圈;接著查快取,查不到就轉交 mNetworkQueue;查到但已過期,同樣轉去網路;命中且未過期時,用 parseNetworkResponse 解析後判斷新鮮度——完全有效就直接 postResponse 回主執行緒,只是「軟過期」則先把快取內容當成中間結果回送,再把請求丟進 mNetworkQueue 去做驗證更新。
文字描述繞口,看這張流程圖會清楚很多:

快取撐不住的任務就交給它。run() 同樣是無窮迴圈:
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)); } } } 從佇列取任務、檢查是否已取消,然後 mNetwork.performRequest() 真的送出連線。若伺服器回 304 而且這個請求先前已經回送過結果,就代表那只是快取驗證的附帶請求,直接重新迴圈;否則解析回應、視情況寫入快取,最後交給 mDelivery 回送。

兩個 Dispatcher 拿到資料後,都靠 mDelivery.postResponse(request, response) 送回。由於 Dispatcher 跑在自己的執行緒上,資料必須想辦法跨回主執行緒,mDelivery 的型別是 ExecutorDelivery:
public void postResponse(Request<?> request, Response<?> response) { postResponse(request, response, null); } public void postResponse(Request<?> request, Response<?> response, Runnable runnable) { request.markDelivered(); request.addMarker("post-response"); mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, runnable)); } 關鍵是最後那行:mResponsePoster 是一個 Executor 物件。
private final Executor mResponsePoster; public ExecutorDelivery(final Handler handler) { // Make an Executor that just wraps the handler. mResponsePoster = new Executor() { @Override public void execute(Runnable command) { handler.post(command); } }; Executor 是線程池框架的介面,只有一個 execute() 方法,而這裡的實作就是把 Runnable 丟給 handler.post()。request 與 response 會被包裝成 ResponseDeliveryRunnable,本身就是個 Runnable。那這個 handler 從哪來?回到 RequestQueue 的建構:mDelivery = new ExecutorDelivery(new Handler(Looper.getMainLooper())),也就是綁在主執行緒 MessageQueue 上的那個 Handler,資料因此得以安全送回主執行緒。
整體看下來,Volley 的骨架就是:請求進佇列 → CacheDispatcher 先問快取 → 未命中或過期轉給 NetworkDispatcher → 回應解析後視情況寫回快取 → 透過綁定主執行緒的 Handler 回送結果。下面這張圖把整個流程串起來:

OpenCV 使用 Harris 演算法實作角點檢測
效果展示 下面先觀察 Harris 角點檢測在圖像上的實際輸出。角點通常會以圓點標記,越明顯的交會區域,響應值越高。 什麼是 Harris 角點檢測 角點可以理解為兩
Android 自訂電量顯示控件的實作
電量自訂控件的實作 這個範例實作一個可以顯示電量的自訂 View。畫面中有一個輸入框,輸入數值後點擊刷新,電池圖示會依比例顯示對應電量。 自訂 BatteryStat
告別 USB 線:用 ADB Wireless 無線調試 Android 手機
前幾天電腦的 USB 接口突然罷工,插線死活連不上手機,眼看著 Eclipse 裡的 Devices 視圖空空如也,Logcat 也抓不到任何訊息,實在令人心浮氣躁。既然
Android-Universal-Image-Loader 源碼深度解讀
Universal-Image-Loader 是一個強大且靈活的 Android 圖片加載、緩存與顯示庫,提供了豐富的配置選項,使用起來十分便捷。 一、基本概念 1.