Volley源碼分析(一)流程

13年的google的I/O大會上驯击,google發(fā)布了Volley烁兰,適用于數(shù)量多但是數(shù)據(jù)量不大的網(wǎng)絡(luò)請求框架,雖然google早已經(jīng)不維護了徊都,但是其中的代碼風格和設(shè)計風格都是值得我們學習的

簡單說一下流程:
首先通過Volley的靜態(tài)方法newRequestQueue()初始化一些參數(shù)沪斟,包括直接發(fā)起請求的HttpStack對象,通過HttpStack對象作為參數(shù)間接對請求加以處理的NetWork對象碟贾,一個本地的緩存對象CaChe币喧,以及以CaChe和NetWork為參數(shù)的我們直接操縱的請求隊列RequestQueue。
在RequestQueue的構(gòu)造器中袱耽,除了上面的兩個參數(shù)杀餐,還有一個處理發(fā)送請求響應(yīng)的ResponseDelivery對象,以及一個數(shù)量為4的處理網(wǎng)絡(luò)請求的線程池NetworkDispatcher調(diào)度器朱巨,還有兩個個成員變量網(wǎng)絡(luò)請求隊列和緩存隊列史翘,均為PriorityBlockingQueue類型。
以RequestQueue.start()作為開始冀续,創(chuàng)建4個網(wǎng)絡(luò)請求對象NetworkDispatcher以及一個請求緩存對象CacheDispatcher琼讽,兩者均繼承于Thread對象,內(nèi)部都寫有一個死循環(huán)洪唐,用戶不斷地從網(wǎng)絡(luò)請求隊列PriorityBlockingQueue拿出或是加入換粗隊列之中钻蹬,最后將從網(wǎng)絡(luò)請求隊列中的請求通過NetWork進行網(wǎng)絡(luò)通信,然后將響應(yīng)通過ResponseDelivery發(fā)送出去凭需,用于我們接收處理问欠。因為Request是面向接口編程肝匆,對于Request我們可以自己定制。

Part1 RequestQueue的初始操作:

通常情況下只調(diào)用參數(shù)為Context的newRequestQueue方法即可:


    /**
     * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
     *
     * @param context A {@link Context} to use for creating the cache dir.
     * @return A started {@link RequestQueue} instance.
     */
    public static RequestQueue newRequestQueue(Context context) {
        return newRequestQueue(context, (BaseHttpStack) null);
    }

因為最后都會調(diào)用到:


    /**
     * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
     *
     * @param context A {@link Context} to use for creating the cache dir.
     * @param stack An {@link HttpStack} to use for the network, or null for default.
     * @return A started {@link RequestQueue} instance.
     * @deprecated Use {@link #newRequestQueue(Context, BaseHttpStack)} instead to avoid depending
     *             on Apache HTTP. This method may be removed in a future release of Volley.
     */
    @Deprecated
    @SuppressWarnings("deprecation")
    public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
        if (stack == null) {
            return newRequestQueue(context, (BaseHttpStack) null);
        }
        return newRequestQueue(context, new BasicNetwork(stack));
    }

其中顺献,因為httpClient和HttpUrlConnection的原因旗国,在初始化HttpStack的時候會有一些出入

 /**
     * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
     *
     * @param context A {@link Context} to use for creating the cache dir.
     * @param stack A {@link BaseHttpStack} to use for the network, or null for default.
     * @return A started {@link RequestQueue} instance.
     */
    public static RequestQueue newRequestQueue(Context context, BaseHttpStack stack) {
        BasicNetwork network;
        if (stack == null) {
            if (Build.VERSION.SDK_INT >= 9) {
                network = new BasicNetwork(new HurlStack());
            } else {
                // Prior to Gingerbread, HttpUrlConnection was unreliable.
                // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
                // At some point in the future we'll move our minSdkVersion past Froyo and can
                // delete this fallback (along with all Apache HTTP code).
                String userAgent = "volley/0";
                try {
                    String packageName = context.getPackageName();
                    PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
                    userAgent = packageName + "/" + info.versionCode;
                } catch (NameNotFoundException e) {
                }

                network = new BasicNetwork(
                        new HttpClientStack(AndroidHttpClient.newInstance(userAgent)));
            }
        } else {
            network = new BasicNetwork(stack);
        }

        return newRequestQueue(context, network);
    }

因為在api<9之前只有httpclient,但是使用難度太大注整,所以谷歌在api=9的時候重新實現(xiàn)了一個網(wǎng)絡(luò)請求類HttpURLConnection能曾,雖然還有些問題,但是相對于谷歌現(xiàn)在已經(jīng)放棄對httpClient的維護了肿轨,所以大家可以盡情的使用寿冕,有興趣的同學可自行百度拓展,限于篇幅和本章側(cè)重點就不多說了萝招。
所以這段代碼主要是聲明了網(wǎng)絡(luò)請求的實現(xiàn)類BasicNetWork蚂斤。
我們進入HttpClientStack存捺,可以看到其實現(xiàn)了HttpStack接口槐沼,以及一個HttpClient對象


/**
 * An HttpStack that performs request over an {@link HttpClient}.
 *
 * @deprecated The Apache HTTP library on Android is deprecated. Use {@link HurlStack} or another
 *             {@link BaseHttpStack} implementation.
 */
@Deprecated
public class HttpClientStack implements HttpStack {
    protected final HttpClient mClient;

進入HUrlStack 我們可以看到其最終也是實現(xiàn)了HttpStack接口:

/**
 * An {@link HttpStack} based on {@link HttpURLConnection}.
 */
public class HurlStack extends BaseHttpStack {

/** An HTTP stack abstraction. */
@SuppressWarnings("deprecation") // for HttpStack
public abstract class BaseHttpStack implements HttpStack {

在HttpStack中我們可以看到 只有一個抽象方法performRequest(),參數(shù)為Request類型的請求和一個Map類型的請求頭:


/**
 * An HTTP stack abstraction.
 *
 * @deprecated This interface should be avoided as it depends on the deprecated Apache HTTP library.
 *     Use {@link BaseHttpStack} to avoid this dependency. This class may be removed in a future
 *     release of Volley.
 */
@Deprecated
public interface HttpStack {
    /**
     * Performs an HTTP request with the given parameters.
     *
     * <p>A GET request is sent if request.getPostBody() == null. A POST request is sent otherwise,
     * and the Content-Type header is set to request.getPostBodyContentType().</p>
     *
     * @param request the request to perform
     * @param additionalHeaders additional headers to be sent together with
     *         {@link Request#getHeaders()}
     * @return the HTTP response
     */
    HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError;

}

接著往下看捌治,在performRequest()中我們看到了httpclient調(diào)用execute發(fā)起了請求


    @Override
    public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
            throws IOException, AuthFailureError {
        HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
        addHeaders(httpRequest, additionalHeaders);
        addHeaders(httpRequest, request.getHeaders());
        onPrepareRequest(httpRequest);
        HttpParams httpParams = httpRequest.getParams();
        int timeoutMs = request.getTimeoutMs();
        // TODO: Reevaluate this connection timeout based on more wide-scale
        // data collection and possibly different for wifi vs. 3G.
        HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
        HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
        return mClient.execute(httpRequest);
    }

所以我們肯定在HUrlStack和HttpClientStack中的performRequest則是具體的網(wǎng)絡(luò)請求岗钩,一個是用HttpUrlConnection,一個則是用HttpClient

HttpClientStack中的請求方法


    @Override
    public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
            throws IOException, AuthFailureError {
        HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
        addHeaders(httpRequest, additionalHeaders);
        addHeaders(httpRequest, request.getHeaders());
        onPrepareRequest(httpRequest);
        HttpParams httpParams = httpRequest.getParams();
        int timeoutMs = request.getTimeoutMs();
        // TODO: Reevaluate this connection timeout based on more wide-scale
        // data collection and possibly different for wifi vs. 3G.
        HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
        HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
        return mClient.execute(httpRequest);
    }

因為在BaseHttpStack中將perfornRequest廢棄掉了肖油,重新new了一個抽象executeRequest()


/** An HTTP stack abstraction. */
@SuppressWarnings("deprecation") // for HttpStack
public abstract class BaseHttpStack implements HttpStack {

    /**
     * Performs an HTTP request with the given parameters.
     *
     * <p>A GET request is sent if request.getPostBody() == null. A POST request is sent otherwise,
     * and the Content-Type header is set to request.getPostBodyContentType().
     *
     * @param request the request to perform
     * @param additionalHeaders additional headers to be sent together with
     *         {@link Request#getHeaders()}
     * @return the {@link HttpResponse}
     * @throws SocketTimeoutException if the request times out
     * @throws IOException if another I/O error occurs during the request
     * @throws AuthFailureError if an authentication failure occurs during the request
     */
    public abstract HttpResponse executeRequest(
            Request<?> request, Map<String, String> additionalHeaders)
            throws IOException, AuthFailureError;

    /**
     * @deprecated use {@link #executeRequest} instead to avoid a dependency on the deprecated
     * Apache HTTP library. Nothing in Volley's own source calls this method. However, since
     * {@link BasicNetwork#mHttpStack} is exposed to subclasses, we provide this implementation in
     * case legacy client apps are dependent on that field. This method may be removed in a future
     * release of Volley.
     */
    @Deprecated
    @Override
    public final org.apache.http.HttpResponse performRequest(
            Request<?> request, Map<String, String> additionalHeaders)
            throws IOException, AuthFailureError {
              ....
              ....
        return apacheResponse;
    }

所以在HUrlStack中的具體實現(xiàn)則是:


    @Override
    public HttpResponse executeRequest(Request<?> request, Map<String, String> additionalHeaders)
            throws IOException, AuthFailureError {
        String url = request.getUrl();
        HashMap<String, String> map = new HashMap<>();
        map.putAll(request.getHeaders());
        map.putAll(additionalHeaders);
        if (mUrlRewriter != null) {
            String rewritten = mUrlRewriter.rewriteUrl(url);
            if (rewritten == null) {
                throw new IOException("URL blocked by rewriter: " + url);
            }
            url = rewritten;
        }
        URL parsedUrl = new URL(url);
        HttpURLConnection connection = openConnection(parsedUrl, request);
        for (String headerName : map.keySet()) {
            connection.addRequestProperty(headerName, map.get(headerName));
        }
        setConnectionParametersForRequest(connection, request);
        // Initialize HttpResponse with data from the HttpURLConnection.
        int responseCode = connection.getResponseCode();
        if (responseCode == -1) {
            // -1 is returned by getResponseCode() if the response code could not be retrieved.
            // Signal to the caller that something was wrong with the connection.
            throw new IOException("Could not retrieve response code from HttpUrlConnection.");
        }

        if (!hasResponseBody(request.getMethod(), responseCode)) {
            return new HttpResponse(responseCode, convertHeaders(connection.getHeaderFields()));
        }

        return new HttpResponse(responseCode, convertHeaders(connection.getHeaderFields()),
                connection.getContentLength(), inputStreamFromConnection(connection));
    }

回到volley兼吓,我們看下RequestQueue的構(gòu)造器:


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

Cache和NetWrok使我們在volley中實現(xiàn)的對象,第三個是線程的數(shù)量森枪,volley默認的4视搏,當然也可以手動設(shè)置,第四個參數(shù)則是處理響應(yīng)的對象县袱,可以看下實現(xiàn):

    /**
     * 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
     */
    public RequestQueue(Cache cache, Network network, int threadPoolSize) {
        this(cache, network, threadPoolSize,
                new ExecutorDelivery(new Handler(Looper.getMainLooper())));
    }

可以看到浑娜,在實例化ExecutorDelivery的時候,包含有一個主線程Looper的Hnalder對象式散,開頭有說過筋遭,delivery是將我們的請求響應(yīng)進行處理,帶著這一目標我們進入ExecutorDelivery類看看:

 /**
     * Creates a new response delivery interface.
     * @param handler {@link Handler} to post responses on
     */
    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);
            }
        };
    }

在它的構(gòu)造器里可以看到實現(xiàn)了一個Executor對象暴拄,并將其Runnable作為參數(shù)漓滔,在主線程中去進行操作,那我們可以簡單推測一下乖篷,這個Runnable里面應(yīng)該就是包含著響應(yīng)的處理任務(wù):

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

    @Override
    public void postError(Request<?> request, VolleyError error) {
        request.addMarker("post-error");
        Response<?> response = Response.error(error);
        mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, null));
    }

這三個是方法是繼承于ExecuteDelivery的父類响驴,里面的代碼是將一個Runnable對象通過mResponsePoster發(fā)送到主線程,這個mResponsePoster就是我們在構(gòu)造器里面實現(xiàn)的對象撕蔼,我們再一起去看看Runnable的實現(xiàn)類 ResponseDeliveryRunnable:

/**
     * A Runnable used for delivering network responses to a listener on the
     * main thread.
     */
    @SuppressWarnings("rawtypes")
    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() {
            // NOTE: If cancel() is called off the thread that we're currently running in (by
            // default, the main thread), we cannot guarantee that deliverResponse()/deliverError()
            // won't be called, since it may be canceled after we check isCanceled() but before we
            // deliver the response. Apps concerned about this guarantee must either call cancel()
            // from the same thread or implement their own guarantee about not invoking their
            // listener after cancel() has been called.

            // 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()里面的意思很明顯 如果response成功了 就通過request發(fā)送一個成功的回調(diào)豁鲤,如果失敗了就通過request發(fā)送一個失敗的回調(diào)石蔗,并結(jié)束掉Request。
我們來看一下這兩個回調(diào)畅形,以StringRequest為例:

 @Override
    protected void deliverResponse(String response) {
        Response.Listener<String> listener;
        synchronized (mLock) {
            listener = mListener;
        }
        if (listener != null) {
            listener.onResponse(response);
        }
    }

在StringRequest中只是實現(xiàn)了成功的回調(diào)养距,失敗的回調(diào)在Request父類之中,
mListerner則是我們在最初實例化StringRequest的時候手動傳進來的參數(shù)日熬,然后通過這個監(jiān)聽調(diào)用onResponse方法棍厌,并將我們的響應(yīng)結(jié)果放進去,因為這里是一StringRequest為例竖席,所以Listener類型是String類型的耘纱,這樣我們就可以直接拿到響應(yīng)結(jié)果了,失敗的回調(diào)一樣毕荐,我們再來回顧下我們通常情況下使用Volley的寫法:

  //1束析、創(chuàng)建請求隊列
    RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
    /**2、實例化StringRequest請求
     *  第一個參數(shù)選擇Request.Method.GET即get請求方式
     *  第二個參數(shù)的url地址根據(jù)文檔所給
     *  第三個參數(shù)Response.Listener 請求成功的回調(diào)
     *  第四個參數(shù)Response.ErrorListener 請求失敗的回調(diào)
     */
    StringRequest stringRequest = new StringRequest(Request.Method.GET,"https:xxx",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    //String s即為服務(wù)器返回的數(shù)據(jù)
                    Log.d("cylog", s);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            Log.e("cylog", volleyError.getMessage(),volleyError);
        }
    });
    //3憎亚、將請求添加進請求隊列
        requestQueue.add(stringRequest);

到現(xiàn)在员寇,ExecutorDelivery發(fā)送請求響應(yīng)這條路算是打通了。
Part2 Volley的運作
我們在初始化并拿到RequestQueue之后第美,通過ReqeustQueue.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();
        }
    }

    /**
     * Stops the cache and network dispatchers.
     */
    public void stop() {
        if (mCacheDispatcher != null) {
            mCacheDispatcher.quit();
        }
        for (final NetworkDispatcher mDispatcher : mDispatchers) {
            if (mDispatcher != null) {
                mDispatcher.quit();
            }
        }
    }

在正式運作之前,先要確保所有的請求調(diào)度器已停止運作什往,所以也就要求我們RequestQueue需要全局只有一個扳缕。
start()只做了兩件事,創(chuàng)建一個Thread類型的緩存網(wǎng)絡(luò)調(diào)度器别威,以及創(chuàng)建四個Thread類型的網(wǎng)絡(luò)調(diào)度器躯舔。
我們先來看下NetworkDispatcher 的run方法:

   @Override
    public void run() {
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        while (true) {
            try {
                processRequest();
            } catch (InterruptedException e) {
                // We may have been interrupted because it was time to quit.
                if (mQuit) {
                    return;
                }
            }
        }
    }

里面有一個死循環(huán),不停的調(diào)用processRequest方法省古,再來看下processRequest

 // Extracted to its own method to ensure locals have a constrained liveness scope by the GC.
    // This is needed to avoid keeping previous request references alive for an indeterminate amount
    // of time. Update consumer-proguard-rules.pro when modifying this. See also
    // https://github.com/google/volley/issues/114
    private void processRequest() throws InterruptedException {
        // Take a request from the queue.
       // 從請求隊列中拿出一個請求
        Request<?> request = mQueue.take();

        long startTimeMs = SystemClock.elapsedRealtime();
        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");
                request.notifyListenerResponseNotUsable();
                return;
            }

            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");
                request.notifyListenerResponseNotUsable();
                return;
            }

            // 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);
            request.notifyListenerResponseReceived(response);
        } catch (VolleyError volleyError) {
            volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
            parseAndDeliverNetworkError(request, volleyError);
            request.notifyListenerResponseNotUsable();
        } 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);
            request.notifyListenerResponseNotUsable();
        }
    }

這個方法首先是從緩存網(wǎng)絡(luò)隊列中拿出一個請求粥庄,如果這個請求已經(jīng)被取消,則將這個請求finish掉衫樊,并加一個一個標識飒赃,然后退出本次循環(huán),繼續(xù)從隊列中取出下一個請求科侈。如果這個請求沒有被取消礁芦,則通過NetWork發(fā)送請求闭翩,進行網(wǎng)絡(luò)通信颗管,并返回一個NetWorkResponse類型的響應(yīng):

            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);

然后將這個響應(yīng)通過request的parseNetworkResponse方法進行處理玫锋,parseNetworkResponse方法是每個request子類必須要實現(xiàn)的方法,用以將響應(yīng)封裝成我們想要的格式权薯,比如String姑躲,比如Json等等睡扬,最后返回一個Response<?>類型的對象,然后加一個標識黍析。
如果這個請求允許被緩存卖怜,并且響應(yīng)的Cache.Entity不為空的話就將這個請求的url為key,Cache.Entity為Value存儲在本地緩存中阐枣。
然后我們再去看下NetworkDispatcher:

   @Override
    public void run() {
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        while (true) {
            try {
                processRequest();
            } catch (InterruptedException e) {
                // We may have been interrupted because it was time to quit.
                if (mQuit) {
                    return;
                }
            }
        }
    }

同樣的马靠,它也繼承于Thread,并且在run里面也是一個死循環(huán)蔼两,不停的調(diào)用processRequest()甩鳄。不同的是,緩存調(diào)度器里面的是一直不斷從緩存隊列中讀取請求额划,網(wǎng)絡(luò)調(diào)度器是不斷的從網(wǎng)絡(luò)隊列中讀取請求:

        final Request<?> request = mCacheQueue.take();
        Request<?> request = mQueue.take();

ok妙啃,我們再來看看請求的添加,也就是RequestQueue的.add方法:

 /**
     * Adds a Request to the dispatch queue.
     * @param request The request to service
     * @return The passed-in request
     */
    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;
        }
        mCacheQueue.add(request);
        return request;
     }

邏輯很簡單俊戳,如果請求可以被緩存揖赴,就將緩存存放到緩存隊列之中,如果不可以被緩存品抽,則放入到網(wǎng)絡(luò)請求隊列之中储笑。

至此甜熔,Volley的流程是走完了圆恤。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市腔稀,隨后出現(xiàn)的幾起案子盆昙,更是在濱河造成了極大的恐慌,老刑警劉巖焊虏,帶你破解...
    沈念sama閱讀 206,723評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件淡喜,死亡現(xiàn)場離奇詭異,居然都是意外死亡诵闭,警方通過查閱死者的電腦和手機炼团,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,485評論 2 382
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來疏尿,“玉大人瘟芝,你說我怎么就攤上這事∪焖觯” “怎么了锌俱?”我有些...
    開封第一講書人閱讀 152,998評論 0 344
  • 文/不壞的土叔 我叫張陵,是天一觀的道長敌呈。 經(jīng)常有香客問我贸宏,道長造寝,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,323評論 1 279
  • 正文 為了忘掉前任吭练,我火速辦了婚禮诫龙,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘鲫咽。我一直安慰自己赐稽,他們只是感情好,可當我...
    茶點故事閱讀 64,355評論 5 374
  • 文/花漫 我一把揭開白布浑侥。 她就那樣靜靜地躺著姊舵,像睡著了一般。 火紅的嫁衣襯著肌膚如雪寓落。 梳的紋絲不亂的頭發(fā)上括丁,一...
    開封第一講書人閱讀 49,079評論 1 285
  • 那天,我揣著相機與錄音伶选,去河邊找鬼史飞。 笑死,一個胖子當著我的面吹牛仰税,可吹牛的內(nèi)容都是我干的构资。 我是一名探鬼主播,決...
    沈念sama閱讀 38,389評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼陨簇,長吁一口氣:“原來是場噩夢啊……” “哼吐绵!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起河绽,我...
    開封第一講書人閱讀 37,019評論 0 259
  • 序言:老撾萬榮一對情侶失蹤己单,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后耙饰,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體纹笼,經(jīng)...
    沈念sama閱讀 43,519評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,971評論 2 325
  • 正文 我和宋清朗相戀三年苟跪,在試婚紗的時候發(fā)現(xiàn)自己被綠了廷痘。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,100評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡件已,死狀恐怖笋额,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情拨齐,我是刑警寧澤鳞陨,帶...
    沈念sama閱讀 33,738評論 4 324
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響厦滤,放射性物質(zhì)發(fā)生泄漏援岩。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,293評論 3 307
  • 文/蒙蒙 一掏导、第九天 我趴在偏房一處隱蔽的房頂上張望享怀。 院中可真熱鬧,春花似錦趟咆、人聲如沸添瓷。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,289評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽鳞贷。三九已至,卻和暖如春虐唠,著一層夾襖步出監(jiān)牢的瞬間搀愧,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,517評論 1 262
  • 我被黑心中介騙來泰國打工疆偿, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留咱筛,地道東北人。 一個月前我還...
    沈念sama閱讀 45,547評論 2 354
  • 正文 我出身青樓杆故,卻偏偏與公主長得像迅箩,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子处铛,可洞房花燭夜當晚...
    茶點故事閱讀 42,834評論 2 345

推薦閱讀更多精彩內(nèi)容

  • Volley源碼分析之流程和緩存 前言 Android一開始提供了HttpURLConnection和HttpCl...
    大寫ls閱讀 612評論 0 6
  • 我的博客: Volley 源碼分析 Volley 的使用流程分析 官網(wǎng)示例 創(chuàng)建一個請求隊列 RequestQue...
    realxz閱讀 2,034評論 1 11
  • 前言 本文是一篇日常學習總結(jié)性的文章饲趋,筆者通過分析經(jīng)典網(wǎng)絡(luò)框架Volley的源碼,望以鞏固Android網(wǎng)絡(luò)框架中...
    Armstrong_Q閱讀 567評論 0 7
  • 注:本文轉(zhuǎn)自http://codekk.com/open-source-project-analysis/deta...
    Ten_Minutes閱讀 1,287評論 1 16
  • 法語認識不多 看到的是bon罢缸,confiance篙贸,plasir 還是很棒的 懶得發(fā)祝福但是又…… 為了人情 畢竟長...
    去社閱讀 83評論 1 0