Volley源碼解析

volley翅溺,應該是Android開源框架中最簡單的框架了饵史,同時它也是最具有代表性的框架。如果你吃透了它嘴拢,那么你看其他的開源框架也會容易很多桩盲。
先上圖:


這里寫圖片描述

從上圖中可以看出,Volley創(chuàng)建了RequestQueue席吴,RequestQueue執(zhí)行Cache和NetWork兩個轉(zhuǎn)發(fā)器赌结,
最終執(zhí)行ExecutorDelivery

下面一步一步開始分析
1.Volley執(zhí)行newRequestQueue

public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
        File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
        .......
        // 根據(jù)版本不同之行不同當網(wǎng)絡請求
        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;
    }

RequestQueue里持有兩個隊列:一個是緩存隊列,一個是網(wǎng)絡隊列

    /** The cache triage queue. */
    private final PriorityBlockingQueue<Request<?>> mCacheQueue =
        new PriorityBlockingQueue<Request<?>>();

    /** The queue of requests that are actually going out to the network. */
    private final PriorityBlockingQueue<Request<?>> mNetworkQueue =
        new PriorityBlockingQueue<Request<?>>();

Volley調(diào)用了start方法孝冒,創(chuàng)建了者兩個隊列柬姚,并同時執(zhí)行

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

我們先看緩存轉(zhuǎn)發(fā)器里主要做了什么

    //首先它是繼承Thread
    CacheDispatcher extends Thread

在run方法里執(zhí)行了:

一直在循環(huán)
    while (true) {
            try {
                // Get a request from the cache triage queue, blocking until
                // 不停的從Cache隊列里取出請求
                final Request<?> request = mCacheQueue.take();
                Cache.Entry entry = mCache.get(request.getCacheKey());
                // 如果從緩存里取不到,則把他放到NetWork隊列
                if (entry == null) {
                    request.addMarker("cache-miss");
                    mNetworkQueue.put(request);
                    continue;
                }

                // 如果從緩存里取出則返回
                request.addMarker("cache-hit");
                Response<?> response = request.parseNetworkResponse(
                        new NetworkResponse(entry.data, entry.responseHeaders));
                request.addMarker("cache-hit-parsed");

                if (!entry.refreshNeeded()) {
                    mDelivery.postResponse(request, response);
                } else {
                    request.addMarker("cache-hit-refresh-needed");
                    request.setCacheEntry(entry);

                    // Mark the response as intermediate.
                    mDelivery.postResponse(request, response, new Runnable() {
                        @Override
                        public void run() {
                            try {
                                mNetworkQueue.put(request);
                            } catch (InterruptedException e) {
                                // Not much we can do about this.
                            }
                        }
                    });
                }

NetWorkDispatch,實際就是發(fā)起請求返回結(jié)果

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

從上面兩個Dispatcher中最后都由mDelivery. postResponse
那么它是什么尼庄涡?

mDelivery = new ExecutorDelivery(new Handler(Looper.getMainLooper()))
        mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, runnable));
    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();
            }
       }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末量承,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子穴店,更是在濱河造成了極大的恐慌撕捍,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,539評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件泣洞,死亡現(xiàn)場離奇詭異忧风,居然都是意外死亡,警方通過查閱死者的電腦和手機球凰,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,594評論 3 396
  • 文/潘曉璐 我一進店門狮腿,熙熙樓的掌柜王于貴愁眉苦臉地迎上來该窗,“玉大人,你說我怎么就攤上這事蚤霞⌒锸В” “怎么了?”我有些...
    開封第一講書人閱讀 165,871評論 0 356
  • 文/不壞的土叔 我叫張陵昧绣,是天一觀的道長规肴。 經(jīng)常有香客問我,道長夜畴,這世上最難降的妖魔是什么拖刃? 我笑而不...
    開封第一講書人閱讀 58,963評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮贪绘,結(jié)果婚禮上兑牡,老公的妹妹穿的比我還像新娘。我一直安慰自己税灌,他們只是感情好均函,可當我...
    茶點故事閱讀 67,984評論 6 393
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著菱涤,像睡著了一般苞也。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上粘秆,一...
    開封第一講書人閱讀 51,763評論 1 307
  • 那天如迟,我揣著相機與錄音,去河邊找鬼攻走。 笑死殷勘,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的昔搂。 我是一名探鬼主播玲销,決...
    沈念sama閱讀 40,468評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼巩趁!你這毒婦竟也來了痒玩?” 一聲冷哼從身側(cè)響起淳附,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤议慰,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后奴曙,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體别凹,經(jīng)...
    沈念sama閱讀 45,850評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,002評論 3 338
  • 正文 我和宋清朗相戀三年洽糟,在試婚紗的時候發(fā)現(xiàn)自己被綠了炉菲。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片堕战。...
    茶點故事閱讀 40,144評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖拍霜,靈堂內(nèi)的尸體忽然破棺而出嘱丢,到底是詐尸還是另有隱情,我是刑警寧澤祠饺,帶...
    沈念sama閱讀 35,823評論 5 346
  • 正文 年R本政府宣布越驻,位于F島的核電站,受9級特大地震影響道偷,放射性物質(zhì)發(fā)生泄漏缀旁。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,483評論 3 331
  • 文/蒙蒙 一勺鸦、第九天 我趴在偏房一處隱蔽的房頂上張望并巍。 院中可真熱鬧,春花似錦换途、人聲如沸懊渡。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,026評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽距贷。三九已至,卻和暖如春吻谋,著一層夾襖步出監(jiān)牢的瞬間忠蝗,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,150評論 1 272
  • 我被黑心中介騙來泰國打工漓拾, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留阁最,地道東北人。 一個月前我還...
    沈念sama閱讀 48,415評論 3 373
  • 正文 我出身青樓骇两,卻偏偏與公主長得像速种,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子低千,可洞房花燭夜當晚...
    茶點故事閱讀 45,092評論 2 355

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