Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android Volley完全解析,帶你從源碼的角度理解Volley

Android Volley完全解析,帶你從源碼的角度理解Volley

編輯:關於Android編程

**對於Volley的工作原理,恐怕有很多朋友還不是很清楚。因此,本篇文章中我們就來一起閱讀一下Volley的源碼,將它的工作流程整體地梳理一遍。 其實,Volley的官方文檔中本身就附有了一張Volley的工作流程圖,如下圖所示。**

這裡寫圖片描述

多數朋友突然看到一張這樣的圖,應該會和我一樣,感覺一頭霧水吧?沒錯,目前我們對Volley背後的工作原理還沒有一個概念性的理解,直接就來看這張圖自然會有些吃力。不過沒關系,下面我們就去分析一下Volley的源碼,之後再重新來看這張圖就會好理解多了。
說起分析源碼,那麼應該從哪兒開始看起呢?這就要回顧一下Volley的用法了,還記得嗎,使用Volley的第一步,首先要調用Volley.newRequestQueue(context)方法來獲取一個RequestQueue對象,那麼我們自然要從這個方法開始看起了,代碼如下所示:<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxwcmUgY2xhc3M9"brush:java;"> 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  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> stagedRequests = mWaitingRequests.get(cacheKey);  
            if (stagedRequests == null) {  
                stagedRequests = new LinkedList>();  
            }  
            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 {  

    ……  

    @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中是怎麼處理網絡請求隊列的,代碼如下所示:

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 responseHeaders = new HashMap();  
            try {  
                // Gather headers.  
                Map headers = new HashMap();  
                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的用法和源碼全部學習完了..

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved