1. 程式人生 > >Volley原始碼解析

Volley原始碼解析

@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根據key取出相應的結果entry
Cache.Entry entry = mCache.get(request.getCacheKey());
//如果結果為null,則打上快取消失的標誌,然後把請求加入NetworkQueue,重新進行網路請求
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.
            //如果快取的請求結果已過期,則同樣打個標誌,然後放進NetwoekQueue重新請求
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");
//把結果轉化為NetworkResponse型別
Response<?> response = request.parseNetworkResponse(
                    new NetworkResponse(entry.dataentry.responseHeaders));
request.addMarker("cache-hit-parsed");
//如果結果是不需要重新整理的,則直接傳送給ResponseDelivery進行分發
if (!entry.refreshNeeded()) {
                // Completely unexpired cache hit. Just deliver the response.
mDelivery.postResponse(requestresponse);
}
            //如果結果是需要重新整理的,則也是先把結果傳送給ResponseDelivery進行分發,然後再放進NetworkQueue中進行網路請求
//這樣可以先展示快取的結果,然後又去請求網路回來就可以重新整理結果了
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(requestresponse, 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;
}
    }
}