Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android進階-Volley-2.RequestQueue&NetworkDispatcher

Android進階-Volley-2.RequestQueue&NetworkDispatcher

編輯:關於Android編程

 

 

使用Volley很簡單,過程分為兩步:

1. 建立請求隊列RequestQueue queue = new Volley.newRequestQueue()

2. 新建請求XXRequest,然後將請求加入隊列queue中:queue.add(XXRequest);

一、Volley.newRequestQueue()

新建queue之後只要將各類請求放入該隊列即可,系統會自動對其進行處理。現在先看一下Volley.newRequestQueue做了些什麼:

public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
        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 = new RequestQueue(new DiskBasedCache(cacheDir), network);
        queue.start();

        return queue;
}

該函數中的核心代碼為:

RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
queue.start();

newRequestQueue中的兩個參數分別用於處理緩存請求和網絡請求。這個一會再講。先看後面一句~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();
        }
}

從代碼中可看到,queue.start()的執行開啟了其中的mCacheDispatcher和networkDispatcher,也就是負責處理Cache請求及Network請求的線程。

 

綜上,Volley.newRequestQueue新建了一個請求隊列,並開啟了處理緩存請求的線程mCacheDispatcher和處理網絡請求的線程networkDispatcher。

 

二、NetworkDispatcher& CacheDispatcher

NetworkDispatcher用於處理網絡請求。其構造函數為:

public NetworkDispatcher(BlockingQueue queue,
            Network network, Cache cache,
            ResponseDelivery delivery) {
        mQueue = queue;
        mNetwork = network;
        mCache = cache;
        mDelivery = delivery;
}

現在再回過頭看RequestQueue的start函數,其中有~RequestQueue.java/start():

NetworkDispatchernetworkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,mCache,mDelivery);

這裡的mNetworkQueue 是RequestQueue中定義&分配的~RequestQueue.java:

private final PriorityBlockingQueue mNetworkQueue =
        new PriorityBlockingQueue();

這個由Request組成的BlockingQueue用於存放網絡Request。(RequestQueue中還聲明&定義了一個mCacheQueue,和mNetworkQueue類似,用於存放緩存請求)

現在看下NetworkDispatcher的run函數中執行的功能:

  public void run() {
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        Request request;
        while (true) {
            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;
                }

                // Tag the request (if API >= 14)
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                    TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
                }

                // 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) {
                parseAndDeliverNetworkError(request, volleyError);
            } catch (Exception e) {
                VolleyLog.e(e, Unhandled exception %s, e.toString());
                mDelivery.postError(request, new VolleyError(e));
            }
        }
}

其循環執行while(true)中的內容,大致流程為:從mQueue(即RequestQueue中的mNetworkQueue)中取出一個request(注意,這裡mNetworkQueue的類型是PriorityBlockingQueue,帶優先級的阻塞隊列,即在當mNetworkQueue隊列為空時,本線程為一直阻塞在mQueue.take()這一步,等待直到新的請求到來。)接下來是:if(mQuit) {return; },當線程執行quit時會將mQuit賦值為true,線程退出。這個在這裡不重要,可以先不糾結。之後判斷請求是否被取消,若被取消則重新在mNetworkQueue中取出一個新的Request進行處理;若未被取消,執行NetworkResponse networkResponse = mNetwork.performRequest(request);(之前有段API>=14的判斷,以及一些其他的東西,這裡都先不管,看懂邏輯先)mNetwork是一個Network接口,Network中的performRequest函數負責執行request,並返回一個NetworkResponse。其原型為(Network.java):

public NetworkResponse performRequest(Request request) throws VolleyError;

mNetwork在構造函數中被初始化(RequestQueue.start()):

NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,mCache, mDelivery);

RequestQueue中的mNetwork在其構造函數中被初始化(Volley.newRequestQueue()):

Network network = new BasicNetwork(stack);
RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);

接著用request解析返回的NetworkResponse,返回一個類型為Response的response。之後判斷是否要緩存至cache。最後執行:

request.markDelivered();//將mResponseDelivered置為true,先忽略掉,重點是下面一句

mDelivery.postResponse(request,response);

將結果傳遞到主線程。

CacheDispatcher用於處理緩存請求,這裡先假設使用無緩存的類NoCache,不分析這個東西

 

 

 

綜上,這裡了解了RequestQueue和NetworkDispatcher:

1. Volley.newRequestQueue執行的大致工作:初始化了RequestQueue queue,之後執行的queue.start啟動了mCacheDispatcher線程和X個NetworkDispatcher.線程。

2. 簡述了NetworkDispatcher類:本線程啟動後,在線程停止之前,會不斷從網絡請求隊列mQueue中取出Request,並利用接口Network完成該請求。Network執行請求後返回NetworkResponse,利用request將NetworkResponse解析成Response,最後利用mDelivery傳送結果。類中用到的、未分析的類有:Network、NetworkResponse、Response、mDelivery。留到下次繼續。









  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved