Android进阶-Volley-2.RequestQueue&NetworkDispatcher

参考链接:

http://www.codekk.com/open-source-project-analysis/detail/Android/grumoon/Volley%20%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90

 

使用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<Request> 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<Request> mNetworkQueue =
        new PriorityBlockingQueue<Request>();

这个由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<Request>,带优先级的阻塞队列,即在当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。留到下次继续。









郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。