Android Volley框架原始碼解析

鋸齒流沙發表於2018-01-08

第一次接觸到Volley,給我的印象就是用法很簡潔,簡單。上手很快,使用起來毫無壓力。所以我決定弄清楚裡面的原始碼是如何進行網路請求的,其實表面越簡單的東西,其內部實現起來會越複雜,這次我主要從整體流程來分析。

Volley的使用:首先新建一個管理類,實現單例模式,獲取Volley的網路請求佇列

public static RequestManager getInstance(Context context) {
        if (mInstance == null) {
            synchronized(RequestManager.class)
            {
                if (mInstance == null) {
                    mInstance = new RequestManager(context);
                }
            }
        }
        return mInstance;
    }
複製程式碼
public RequestQueue getRequestQueue() {
    if (reqQueue == null){
        synchronized(RequestManager.class)
        {
            if (reqQueue == null){
                reqQueue = Volley.newRequestQueue(mContext);
            }
        }
    }
    return reqQueue;
}
複製程式碼

加入請求佇列

      public void addRequest(Request<?> request, Object tag) {
    		if (tag != null) {
    			request.setTag(tag);
    		}
    		getRequestQueue().add(request);
    	}
複製程式碼

這時候使用起來就很簡單了,只需要new一個Request物件,設定相應的回撥,然後將Request加入到網路請求佇列就行了。

        StringRequest stringRequest = new StringRequest(url,
                new Listener<String>() {

                    @Override
                    public void onResponse(String response) {

                        // TODO 會調響應完成在這裡做相應的處理
                        
                    }
                }, new ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO 訪問出現錯誤處理
            }
        });
        RequestManager.getInstance(this).addRequest(stringRequest, this);
複製程式碼

以上就是一般的Volley網路請求使用

現在開始我們的Volley原始碼解析

首先我們從獲取網路請求佇列開始Volley.newRequestQueue(mContext);

public static RequestQueue newRequestQueue(Context context) {
        return newRequestQueue(context, null);
    }
複製程式碼
public static RequestQueue newRequestQueue(Context context, HttpStack stack)
    {
    	return newRequestQueue(context, stack, -1);
    }
複製程式碼
public static RequestQueue newRequestQueue(Context context, HttpStack stack, int maxDiskCacheBytes) {
        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;
        if (maxDiskCacheBytes <= -1)
        {
        	// No maximum size specified
        	queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
        }
        else
        {
        	// Disk cache size specified
        	queue = new RequestQueue(new DiskBasedCache(cacheDir, maxDiskCacheBytes), network);
        }

        queue.start();

        return queue;
    }
複製程式碼

可以看到這三個過載的方法,最終會呼叫 newRequestQueue(Context context, HttpStack stack, int maxDiskCacheBytes) { File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);這個方法。 這個方法主要做的事情就是,如果Android版本大於2.2的,stack就會使用HurlStack,否則使用HttpClientStack。 HurlStack是使用HttpURLConnection做網路訪問,HttpClientStack是使用HttpClient網路訪問。這兩個有什麼區別呢?可以看郭霖大神的 Android訪問網路,使用HttpURLConnection還是HttpClient?這篇文章。 然後新建物件Network network = new BasicNetwork(stack); 最後建立網路請求佇列queue = new RequestQueue(new DiskBasedCache(cacheDir), network);,RequestQueue佇列的構造方法也是一個過載方法,最終的構造方法進行賦值。其中threadPoolSize變數預設為開啟4條執行緒。

public RequestQueue(Cache cache, Network network, int threadPoolSize,
            ResponseDelivery delivery) {
        mCache = cache;
        mNetwork = network;
        mDispatchers = new NetworkDispatcher[threadPoolSize];
        mDelivery = delivery;
    }
複製程式碼

我們回到 newRequestQueue(Context context, HttpStack stack, int maxDiskCacheBytes) { File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);中,看到此方法最後會呼叫queue.start();,我們看看queue.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,CacheDispatcher是一個繼承Thread的執行緒,然後開始執行CacheDispatcher,看看CacheDispatcher所做的事情,主要看run()方法

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

        Request<?> request;
        while (true) {
            // release previous request object to avoid leaking request object when mQueue is drained.
            request = null;
            try {
                // Take a request from the queue.
                request = mCacheQueue.take();
            } catch (InterruptedException e) {
                // We may have been interrupted because it was time to quit.
                if (mQuit) {
                    return;
                }
                continue;
            }
            try {
                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.
                    final Request<?> finalRequest = request;
                    mDelivery.postResponse(request, response, new Runnable() {
                        @Override
                        public void run() {
                            try {
                                mNetworkQueue.put(finalRequest);
                            } catch (InterruptedException e) {
                                // Not much we can do about this.
                            }
                        }
                    });
                }
            } catch (Exception e) {
                VolleyLog.e(e, "Unhandled exception %s", e.toString());
            }
        }
    }
複製程式碼

我們看run()方法的主要做的事情:首先拿出佇列頭request = mCacheQueue.take();,然後設定標誌request.addMarker("cache-queue-take"); ,接著從快取中取出響應結果,如果響應結果為空if (entry == null)或者快取失效if (entry.isExpired()),都會加入到網路請求佇列中mNetworkQueue.put(request);,呼叫網路請求獲取結果。如果快取執行緒中取得結果會呼叫ResponseDelivery的postResponse方法。 而ResponseDelivery的實現就是RequestQueue構造方法new出來的ExecutorDelivery物件,我們看下ExecutorDelivery中的postResponse方法的實現。

 @Override
    public void postResponse(Request<?> request, Response<?> response) {
        postResponse(request, response, null);
    }

    @Override
    public void postResponse(Request<?> request, Response<?> response, Runnable runnable) {
        request.markDelivered();
        request.addMarker("post-response");
        mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, runnable));
    }
複製程式碼
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);
            }
        };
    }
複製程式碼

從ExecutorDelivery可以看出,其主要做的事情是:將結果傳送到主執行緒。再看下ResponseDeliveryRunnable做了什麼操作

 @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();
            }
       }
複製程式碼

上面的run方法中最重要的一句是

            if (mResponse.isSuccess()) {
                mRequest.deliverResponse(mResponse.result);
            } else {
                mRequest.deliverError(mResponse.error);
            }
複製程式碼

如果響應成功的話就會呼叫Request的deliverResponse方法,如果錯誤就會呼叫deliverError方法,而這個Request方法就是我們使用時new請求物件,而文章開頭我們使用的時StringRequest這個物件,那麼我們看看StringRequest的deliverResponse方法。

@Override
    protected void deliverResponse(String response) {
        if (mListener != null) {
            mListener.onResponse(response);
        }
    }
複製程式碼

deliverResponse方法的mListener物件就是我們使用時傳進來的回撥介面,所以最終結果我們可以在設定回撥的onResponse方法中使用。

分析到這裡我們就知道了Volley的呼叫流程了,就知道為什麼我們只是簡單的new一個請求物件然後設定回撥,並把請求物件加入請求佇列就可以完成整個網路請求了。


接下來我們在回看queue.start()的網路請求。主要看下面的語句

for (int i = 0; i < mDispatchers.length; i++) {
            NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,
                    mCache, mDelivery);
            mDispatchers[i] = networkDispatcher;
            networkDispatcher.start();
        }
複製程式碼

前面我們知道預設的執行緒數設定時4,所以這裡回迴圈4次,主要還是看回NetworkDispatcher類,同樣NetworkDispatcher也是繼承Thread的執行緒類。 主要看run()方法

@Override
    public void run() {
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        Request<?> request;
        while (true) {
            long startTimeMs = SystemClock.elapsedRealtime();
            // release previous request object to avoid leaking request object when mQueue is drained.
            request = null;
            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);
            }
        }
    }
複製程式碼

run():首先回取出佇列頭request = mQueue.take();獲取request,接著看網路請求最最主要的一句NetworkResponse networkResponse = mNetwork.performRequest(request);這一句呢主要是網路訪問,獲取得到結果。從RequestQueue的newRequestQueue方法中我們可以知道:如果Android版本大於2.2的會使用HttpURLConnection進行網路訪問,否則使用HttpClient。 網路訪問完成之後會對響應結果進行解析Response<?> response = request.parseNetworkResponse(networkResponse);,接著之後將結果放到快取執行緒mCache.put(request.getCacheKey(), response.cacheEntry);,跟快取執行緒一樣 最終呼叫mDelivery.postResponse(request, response);將結果回撥。

至此,整個volley解剖完成,大家應該也知道整體呼叫流程了。如果還有不明白的,可以看下volley官方給出來的這張圖,結合我的分析就一目瞭然了。

volley-request.png

該文章是我看了好幾天的原始碼分析得來的,哪裡分析得不好請大家指出來,相互學習。網上也有很多分析volley的文章,如有雷同,純屬偶合。

相關文章