Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 網絡編程(四):深入源碼剖析 Volley 工作流程

編輯:關於 Android 開發

Android 網絡編程(四):深入源碼剖析 Volley 工作流程


Volley 是 Google 推出的網絡請求庫,以其簡潔的 API 著稱。本文從源碼出發,剖析它的整體架構與請求流程。

1. Volley 結構圖

從結構圖可以看到,Volley 分為三個線程:主線程、緩存調度線程與網絡調度線程。請求會先加入緩存隊列,若找到對應的緩存結果就直接讀取並解析,再回調給主線程;若緩存中沒有結果,則把請求轉入網絡隊列,發送 HTTP 請求、解析響應並寫入緩存,最後回調主線程。

2. 從 RequestQueue 入手

使用 Volley 前,首先要建立 RequestQueue:

RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());

這也是 Volley 運作的入口。看看 newRequestQueue:

public static RequestQueue newRequestQueue(Context context) {
    return newRequestQueue(context, (HttpStack) 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(), "volley");
    String userAgent = "volley/0";
    try {
        String network = context.getPackageName();
        PackageInfo queue = context.getPackageManager().getPackageInfo(network, 0);
        userAgent = network + "/" + queue.versionCode;
    } catch (NameNotFoundException var7) { ; }
    if (stack == null) {
        if (VERSION.SDK_INT >= 9) {
            stack = new HurlStack();
        } else {
            stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        }
    }
    BasicNetwork network1 = new BasicNetwork((HttpStack) stack);
    RequestQueue queue1;
    if (maxDiskCacheBytes <= -1) {
        queue1 = new RequestQueue(new DiskBasedCache(cacheDir), network1);
    } else {
        queue1 = new RequestQueue(new DiskBasedCache(cacheDir, maxDiskCacheBytes), network1);
    }
    queue1.start();
    return queue1;
}

可見當 Android 版本 ≥ 2.3 時使用基於 HttpURLConnection 的 HurlStack,否則使用基於 HttpClient 的 HttpClientStack。建立 RequestQueue 後呼叫 start():

public void start() {
    this.stop();
    this.mCacheDispatcher = new CacheDispatcher(this.mCacheQueue, this.mNetworkQueue, this.mCache, this.mDelivery);
    this.mCacheDispatcher.start();
    for (int i = 0; i < this.mDispatchers.length; ++i) {
        NetworkDispatcher networkDispatcher = new NetworkDispatcher(this.mNetworkQueue, this.mNetwork, this.mCache, this.mDelivery);
        this.mDispatchers[i] = networkDispatcher;
        networkDispatcher.start();
    }
}

CacheDispatcher 是緩存調度線程,迴圈中啟動的 NetworkDispatcher 是網絡調度線程。預設 mDispatchers.length 為 4,也就是說後台共有 5 個線程在等待請求到來。

接著建立各種 Request 並呼叫 add():

public  Request add(Request request) {
    request.setRequestQueue(this);
    synchronized (this.mCurrentRequests) { this.mCurrentRequests.add(request); }
    request.setSequence(this.getSequenceNumber());
    request.addMarker("add-to-queue");
    // 若不能緩存,直接加入網絡請求隊列
    if (!request.shouldCache()) {
        this.mNetworkQueue.add(request);
        return request;
    } else {
        synchronized (this.mWaitingRequests) {
            String cacheKey = request.getCacheKey();
            // 若有相同請求尚未返回,則暫存,不重複請求
            if (this.mWaitingRequests.containsKey(cacheKey)) {
                Object stagedRequests = this.mWaitingRequests.get(cacheKey);
                if (stagedRequests == null) { stagedRequests = new LinkedList(); }
                ((Queue) stagedRequests).add(request);
                this.mWaitingRequests.put(cacheKey, stagedRequests);
            } else {
                // 否則加入緩存隊列,並記錄以供去重
                this.mWaitingRequests.put(cacheKey, null);
                this.mCacheQueue.add(request);
            }
            return request;
        }
    }
}

可以看到 add() 本身並不真正發請求,只是把任務放入相應隊列。當後台的網絡或緩存調度線程輪詢到請求,才會開始執行。

3. CacheDispatcher 緩存調度線程

它從緩存隊列取出請求,判斷是否被取消;若無則檢查是否有緩存響應,若有且未過期,就解析並回調主線程;若無或過期,則轉入網絡隊列。核心邏輯如下:

final Request e = (Request) this.mCacheQueue.take();
if (e.isCanceled()) {
    e.finish("cache-discard-canceled");
} else {
    Entry entry = this.mCache.get(e.getCacheKey());
    if (entry == null) {
        e.addMarker("cache-miss");
        this.mNetworkQueue.put(e);
    } else if (!entry.isExpired()) {
        e.addMarker("cache-hit");
        Response response = e.parseNetworkResponse(new NetworkResponse(entry.data, entry.responseHeaders));
        if (!entry.refreshNeeded()) {
            this.mDelivery.postResponse(e, response);
        } else {
            // 命中但需刷新,先返回緩存再異步請求網絡
            ...
        }
    } else {
        e.addMarker("cache-hit-expired");
        e.setCacheEntry(entry);
        this.mNetworkQueue.put(e);
    }
}

4. NetworkDispatcher 網絡調度線程

它從隊列取出請求並判斷是否取消,若無則請求網絡、解析響應、寫入緩存,再回調主線程:

request.addMarker("network-queue-take");
if (request.isCanceled()) {
    request.finish("network-discard-cancelled");
} else {
    this.addTrafficStatsTag(request);
    NetworkResponse e = this.mNetwork.performRequest(request);
    if (e.notModified && request.hasHadResponseDelivered()) {
        request.finish("not-modified");
    } else {
        Response volleyError1 = request.parseNetworkResponse(e);
        if (request.shouldCache() && volleyError1.cacheEntry != null) {
            this.mCache.put(request.getCacheKey(), volleyError1.cacheEntry);
        }
        request.markDelivered();
        this.mDelivery.postResponse(request, volleyError1);
    }
}

請求網絡時呼叫 this.mNetwork.performRequest(request),mNetwork 是接口,其實現類是 BasicNetwork。BasicNetwork 內部再透過 HttpStack(實現類為 HurlStack 或 HttpClientStack)真正發起請求,並根據不同的響應狀態碼返回不同的 NetworkResponse。

5. 回調主線程

請求成功後,透過 Delivery 的 postResponse() 把結果回拋主線程:

public void postResponse(Request request, Response response, Runnable runnable) {
    request.markDelivered();
    request.addMarker("post-response");
    this.mResponsePoster.execute(new ExecutorDelivery.ResponseDeliveryRunnable(request, response, runnable));
}

ResponseDeliveryRunnable 在執行時會呼叫 request.deliverResponse(result),這是 Request 抽象類要求子類實作的方法。以 StringRequest 為例:

public class StringRequest extends Request {
    private final Listener mListener;
    protected void deliverResponse(String response) {
        this.mListener.onResponse(response);
    }
}

最終,response 就透過 Response.Listener 的 onResponse() 回調到我們的程式碼中。使用 StringRequest 的典型寫法如下:

RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest mStringRequest = new StringRequest(Request.Method.GET, "https://www.baidu.com",
    new Response.Listener() {
        @Override public void onResponse(String response) {
            Log.i("wangshu", response);
        }
    },
    new Response.ErrorListener() {
        @Override public void onErrorResponse(VolleyError error) {
            Log.e("wangshu", error.getMessage(), error);
        }
    });
mQueue.add(mStringRequest);

看到最後,Volley 從加入隊列、緩存判斷、網絡請求到主線程回調的整個流程應該就清晰了。理解了源碼,才能在實際開發中更好地發揮它的威力。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved