Volley——網絡請求

  Volley做爲當年Google在2013年的Google I/O上的重點,是一個至關給力的框架。它從設計模式上來講,很是具備擴展性,也比較輕巧。關於Volley的使用,網上介紹的不少了,再也不贅述。如今,我將記錄我閱讀Volley源碼的過程,來學習Volley的設計思想和其中的一些小技巧。html

  值的一提的是,新版的gradle已經支持:  java

compile 'com.android.volley:volley:1.0.0'

  這樣導入Volley了。android

  從最簡單的例子看起:設計模式

RequestQueue queue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        queue = Volley.newRequestQueue(this);
        final StringRequest request = new StringRequest("https://www.baidu.com/",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        ((TextView) findViewById(R.id.test_textview_id)).setText(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        findViewById(R.id.test_btn_id).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                queue.add(request);
            }
        });
    }

  能夠看到,一個簡單的Volley的http請求,只須要三步,創建Request隊列--->創建Request請求--->將請求加入Request隊列。緩存

  今天就只看這三步是怎麼運做的。網絡

  咱們先來看看queue = Volley.newRequestQueue(this);app

    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: http://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;
    }

  從體來講這個方法,作了如下幾件事:獲取userAgent、建立HttpStack、建立NetWork、建立並啓動RequestQueue。。框架

  獲取userAgetnt的方法比較簡單 userAgent = packageName + "/" + info.versionCode; 一目瞭然。ide

  接着建立HttpStack和NetWork比較複雜,會單獨記錄。post

  最後會建立一個RequestQueue,做爲請求隊列。而且在初始化時,請求隊列會直接啓動。

 

  接下來,咱們看一下RequestQueue的代碼。咱們先從構造方法開始閱讀:

    /**
     * Creates the worker pool. Processing will not begin until {@link #start()} is called.
     *
     * @param cache A Cache to use for persisting responses to disk
     * @param network A Network interface for performing HTTP requests
     * @param threadPoolSize Number of network dispatcher threads to create
     * @param delivery A ResponseDelivery interface for posting responses and errors
     */
    public RequestQueue(Cache cache, Network network, int threadPoolSize,
            ResponseDelivery delivery) {
        mCache = cache;
        mNetwork = network;
        mDispatchers = new NetworkDispatcher[threadPoolSize];
        mDelivery = delivery;
    }

 

  在初始化時,RequestQueue對4個成員賦了值。緩存、NetWork、網絡分發線程隊列和網絡響應分發接口。 

  下面咱們看看在初始化Volley初始化時,第一個會調用的方法start()

    /**
     * Starts the dispatchers in this queue.
     */
    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();關於stop():

  

    public void stop() {
        if (mCacheDispatcher != null) {
            mCacheDispatcher.quit();
        }
        for (int i = 0; i < mDispatchers.length; i++) {
            if (mDispatchers[i] != null) {
                mDispatchers[i].quit();
            }
        }
    }

 

  它就是經過遍歷,結束了線程中的全部任務。

  咱們能夠在NetworkDispatcher.java中找到相關實現

public void quit() {
    mQuit = true;
    interrupt();
}
public void run() {
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        while (true) {
            long startTimeMs = SystemClock.elapsedRealtime();
            Request<?> request;
            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;
            }
        ......
        }    
}    

 

  繼續看start方法:

  

    /**
     * Starts the dispatchers in this queue.
     */
    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。

  關於NetworkDispatcher中start()方法的實現,NetworkDispatcher繼承了Thread,因此看start()實際上是看run方法:

    @Override
    public void run() {
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        while (true) {
            long startTimeMs = SystemClock.elapsedRealtime();
            Request<?> request;
            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) {
                volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
                parseAndDeliverNetworkError(request, volleyError);
            } catch (Exception e) {
                VolleyLog.e(e, "Unhandled exception %s", e.toString());
                VolleyError volleyError = new VolleyError(e);
                volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
                mDelivery.postError(request, volleyError);
            }
        }
    }

  代碼比較長,咱們分段閱讀。

        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        while (true) {
            long startTimeMs = SystemClock.elapsedRealtime();
            Request<?> request;
            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;
            }

  設置線程優先級爲標準後臺線程,而後進入死循環。雖然這一段代碼沒有什麼實質的實現,可是卻很重要,它基本確立了這個線程的工做模式。這個線程在while(true)的死循環中,每次循環有一次中止線程和一次暫停線程的機會,暫停在前。

  mQueue是個阻塞型隊列。每次循環會在這個隊列裏取一個請求,若是mQueue爲空,取不到請求了,線程就會卡死在這裏,這就是暫停的機會,等到mQueue加入請求時,線程又會從新跑起來。經過這樣的設計,咱們後面發起http請求,只須要往mQueue里加入請求就行了。當調用interrupt方法時,循環就會進入catch分支,而後判斷是否真的要取消,因此咱們在quit()方法中,看到它的實現是先將mQuit置爲true,而後調用interrupt來結束這個線程。

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

  若是請求被取消,則調用請求的finish方法,進入下一輪循環。 而後加入流量標記。咱們能夠看到addTrafficStatsTag

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    private void addTrafficStatsTag(Request<?> request) {
        // 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;
                }

  接着便了Network執行它的performRequest方法,方法的具體實現,將在後面閱讀。經過這個方法,咱們處理了網絡請求,取得了響應——NetworkResponse。下面的一個判斷語句,註釋解釋得很清楚。若是咱們的請求返回304,而且咱們已經分發過這個響應了。咱們將再也不處理響應,結束此次循環,開始下一輪。同時執行request.finish的方法。若是沒有304,那麼咱們還要考慮如何處理響應。

 

                // 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");
                }

 

   這裏,進行解析網絡響應,得到響應——Response。根據配置,若是須要緩存,則將響應的內容緩存在mCache中。

 

                // Post the response back.
                request.markDelivered();
                mDelivery.postResponse(request, response);

 

  最後,根據請求,分析網絡響應。 

  至此,咱們將volley的網絡請求及處理流程基本走通了一遍。後面的文章中,將仔細分析一些Volley對於網絡請求的一些處理細節。

Done

相關文章
相關標籤/搜索