Volley 实现原理深度解析

转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/17656437

参考 volley各个类的各个方法详细的流程图 http://www.cnblogs.com/carlo/articles/4972808.html  值得参考

总体设计图:

这里写图片描述

上面是 Volley 的总体设计图,主要是通过两种Diapatch Thread不断从RequestQueue中取出请求,根据是否已缓存调用Cache或Network这两类数据获取接口之一,从内存缓存或是服务器取得请求的数据,然后交由ResponseDelivery去做结果分发及回调处理。


Volley的工作流程图:




Volley的第一步,调用Volley.newRequestQueue(context)方法来获取一个RequestQueue对象,代码如下所示:

  1. public static RequestQueue newRequestQueue(Context context) {  
  2.     return newRequestQueue(context, null);  
  3. }  
public static RequestQueue newRequestQueue(Context context) {
    return newRequestQueue(context, null);
}
这个方法仅仅只有一行代码,只是调用了newRequestQueue()的方法重载,并给第二个参数传入null。那我们看下带有两个参数的newRequestQueue()方法中的代码,如下所示:
  1. public static RequestQueue newRequestQueue(Context context, HttpStack stack) {  
  2.     File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);  
  3.     String userAgent = "volley/0";  
  4.     try {  
  5.         String packageName = context.getPackageName();  
  6.         PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);  
  7.         userAgent = packageName + "/" + info.versionCode;  
  8.     } catch (NameNotFoundException e) {  
  9.     }  
  10.     if (stack == null) {  
  11.         if (Build.VERSION.SDK_INT >= 9) {  
  12.             stack = new HurlStack();  
  13.         } else {  
  14.             stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));  
  15.         }  
  16.     }  
  17.     Network network = new BasicNetwork(stack);  
  18.     RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);  
  19.     queue.start();  
  20.     return queue;  
  21. }  
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 {
            stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        }
    }
    Network network = new BasicNetwork(stack);
    RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
    queue.start();
    return queue;
}
可以看到,这里在第10行判断如果stack是等于null的,则去创建一个HttpStack对象,这里会判断如果手机系统版本号是大于9的,则创建一个HurlStack的实例,否则就创建一个HttpClientStack的实例。实际上HurlStack的内部就是使用HttpURLConnection进行网络通讯的,而HttpClientStack的内部则是使用HttpClient进行网络通讯的,这里为什么这样选择呢?可以参考Android访问网络,使用HttpURLConnection还是HttpClient?


创建好了HttpStack之后,接下来又创建了一个Network对象,它是用于根据传入的HttpStack对象来处理网络请求的,紧接着new出一个RequestQueue对象,并调用它的start()方法进行启动,然后将RequestQueue返回,这样newRequestQueue()的方法就执行结束了。

Volley的第二步:

那么RequestQueue的start()方法内部到底执行了什么东西呢?我们跟进去瞧一瞧:

public void start() {  
  1.     stop();  // Make sure any currently running dispatchers are stopped.  
  2.     // Create the cache dispatcher and start it.  
  3.     mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);  
  4.     mCacheDispatcher.start();  
  5.     // Create network dispatchers (and corresponding threads) up to the pool size.  
  6.     for (int i = 0; i < mDispatchers.length; i++) {  
  7.         NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,  
  8.                 mCache, mDelivery);  
  9.         mDispatchers[i] = networkDispatcher;  
  10.         networkDispatcher.start();  
  11.     }  
  12. }  
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();
    }
}
这里先是创建了一个CacheDispatcher的实例,然后调用了它的start()方法,接着在一个for循环里去创建NetworkDispatcher的实例,并分别调用它们的start()方法。这里的CacheDispatcher和NetworkDispatcher都是继承自Thread的,而默认情况下for循环会执行四次,也就是说当调用了Volley.newRequestQueue(context)之后,就会有五个线程一直在后台运行,不断等待网络请求的到来,其中CacheDispatcher是缓存线程,NetworkDispatcher是网络请求线程。


Volley的第三步:构建出相应的Request,然后调用RequestQueue的add()方法将Request传入就可以完成网络请求操作了,那么不用说,add()方法的内部肯定有着非常复杂的逻辑,我们来一起看一下:

  1. public <T> Request<T> add(Request<T> request) {  
  2.     // Tag the request as belonging to this queue and add it to the set of current requests.  
  3.     request.setRequestQueue(this);  
  4.     synchronized (mCurrentRequests) {  
  5.         mCurrentRequests.add(request);  
  6.     }  
  7.     // Process requests in the order they are added.  
  8.     request.setSequence(getSequenceNumber());  
  9.     request.addMarker("add-to-queue");  
  10.     // If the request is uncacheable, skip the cache queue and go straight to the network.  
  11.     if (!request.shouldCache()) {  
  12.         mNetworkQueue.add(request);  
  13.         return request;  
  14.     }  
  15.     // Insert request into stage if there's already a request with the same cache key in flight.  
  16.     synchronized (mWaitingRequests) {  
  17.         String cacheKey = request.getCacheKey();  
  18.         if (mWaitingRequests.containsKey(cacheKey)) {  
  19.             // There is already a request in flight. Queue up.  
  20.             Queue<Request<?>> stagedRequests = mWaitingRequests.get(cacheKey);  
  21.             if (stagedRequests == null) {  
  22.                 stagedRequests = new LinkedList<Request<?>>();  
  23.             }  
  24.             stagedRequests.add(request);  
  25.             mWaitingRequests.put(cacheKey, stagedRequests);  
  26.             if (VolleyLog.DEBUG) {  
  27.                 VolleyLog.v("Request for cacheKey=%s is in flight, putting on hold.", cacheKey);  
  28.             }  
  29.         } else {  
  30.             // Insert 'null' queue for this cacheKey, indicating there is now a request in  
  31.             // flight.  
  32.             mWaitingRequests.put(cacheKey, null);  
  33.             mCacheQueue.add(request);  
  34.         }  
  35.         return request;  
  36.     }  
  37. }  
public <T> Request<T> add(Request<T> request) {
    // Tag the request as belonging to this queue and add it to the set of current requests.
    request.setRequestQueue(this);
    synchronized (mCurrentRequests) {
        mCurrentRequests.add(request);
    }
    // Process requests in the order they are added.
    request.setSequence(getSequenceNumber());
    request.addMarker("add-to-queue");
    // If the request is uncacheable, skip the cache queue and go straight to the network.
    if (!request.shouldCache()) {
        mNetworkQueue.add(request);
        return request;
    }
    // Insert request into stage if there's already a request with the same cache key in flight.
    synchronized (mWaitingRequests) {
        String cacheKey = request.getCacheKey();
        if (mWaitingRequests.containsKey(cacheKey)) {
            // There is already a request in flight. Queue up.
            Queue<Request<?>> stagedRequests = mWaitingRequests.get(cacheKey);
            if (stagedRequests == null) {
                stagedRequests = new LinkedList<Request<?>>();
            }
            stagedRequests.add(request);
            mWaitingRequests.put(cacheKey, stagedRequests);
            if (VolleyLog.DEBUG) {
                VolleyLog.v("Request for cacheKey=%s is in flight, putting on hold.", cacheKey);
            }
        } else {
            // Insert 'null' queue for this cacheKey, indicating there is now a request in
            // flight.
            mWaitingRequests.put(cacheKey, null);
            mCacheQueue.add(request);
        }
        return request;
    }
}
可以看到,在第11行的时候会判断当前的请求是否可以缓存,如果不能缓存则在第12行直接将这条请求加入网络请求队列,可以缓存的话则在第33行将这条请求加入缓存队列。在默认情况下,每条请求都是可以缓存的,当然我们也可以调用Request的setShouldCache(false)方法来改变这一默认行为。


OK,那么既然默认每条请求都是可以缓存的,自然就被添加到了缓存队列中,于是一直在后台等待的缓存线程就要开始运行起来了,我们看下CacheDispatcher中的run()方法,代码如下所示:

  1. public class CacheDispatcher extends Thread {  
  2.   
  3.     ……  
  4.   
  5.     @Override  
  6.     public void run() {  
  7.         if (DEBUG) VolleyLog.v("start new dispatcher");  
  8.         Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);  
  9.         // Make a blocking call to initialize the cache.  
  10.         mCache.initialize();  
  11.         while (true) {  
  12.             try {  
  13.                 // Get a request from the cache triage queue, blocking until  
  14.                 // at least one is available.  
  15.                 final Request<?> request = mCacheQueue.take();  
  16.                 request.addMarker("cache-queue-take");  
  17.                 // If the request has been canceled, don't bother dispatching it.  
  18.                 if (request.isCanceled()) {  
  19.                     request.finish("cache-discard-canceled");  
  20.                     continue;  
  21.                 }  
  22.                 // Attempt to retrieve this item from cache.  
  23.                 Cache.Entry entry = mCache.get(request.getCacheKey());  
  24.                 if (entry == null) {  
  25.                     request.addMarker("cache-miss");  
  26.                     // Cache miss; send off to the network dispatcher.  
  27.                     mNetworkQueue.put(request);  
  28.                     continue;  
  29.                 }  
  30.                 // If it is completely expired, just send it to the network.  
  31.                 if (entry.isExpired()) {  
  32.                     request.addMarker("cache-hit-expired");  
  33.                     request.setCacheEntry(entry);  
  34.                     mNetworkQueue.put(request);  
  35.                     continue;  
  36.                 }  
  37.                 // We have a cache hit; parse its data for delivery back to the request.  
  38.                 request.addMarker("cache-hit");  
  39.                 Response<?> response = request.parseNetworkResponse(  
  40.                         new NetworkResponse(entry.data, entry.responseHeaders));  
  41.                 request.addMarker("cache-hit-parsed");  
  42.                 if (!entry.refreshNeeded()) {  
  43.                     // Completely unexpired cache hit. Just deliver the response.  
  44.                     mDelivery.postResponse(request, response);  
  45.                 } else {  
  46.                     // Soft-expired cache hit. We can deliver the cached response,  
  47.                     // but we need to also send the request to the network for  
  48.                     // refreshing.  
  49.                     request.addMarker("cache-hit-refresh-needed");  
  50.                     request.setCacheEntry(entry);  
  51.                     // Mark the response as intermediate.  
  52.                     response.intermediate = true;  
  53.                     // Post the intermediate response back to the user and have  
  54.                     // the delivery then forward the request along to the network.  
  55.                     mDelivery.postResponse(request, response, new Runnable() {  
  56.                         @Override  
  57.                         public void run() {  
  58.                             try {  
  59.                                 mNetworkQueue.put(request);  
  60.                             } catch (InterruptedException e) {  
  61.                                 // Not much we can do about this.  
  62.                             }  
  63.                         }  
  64.                     });  
  65.                 }  
  66.             } catch (InterruptedException e) {  
  67.                 // We may have been interrupted because it was time to quit.  
  68.                 if (mQuit) {  
  69.                     return;  
  70.                 }  
  71.                 continue;  
  72.             }  
  73.         }  
  74.     }  
  75. }  
public class CacheDispatcher extends Thread {

    ……

    @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.Entry entry = mCache.get(request.getCacheKey());
                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.
                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");
                Response<?> response = request.parseNetworkResponse(
                        new NetworkResponse(entry.data, entry.responseHeaders));
                request.addMarker("cache-hit-parsed");
                if (!entry.refreshNeeded()) {
                    // Completely unexpired cache hit. Just deliver the response.
                    mDelivery.postResponse(request, response);
                } 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(request, response, 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;
            }
        }
    }
}
mCacheQueue.take(): 使用Java的BlockingQueue,实现生产者-消费者模式,put方法(满了会阻塞当前线程)和take方法(为空会阻塞当前线程)add(满了会抛出异常)
PriorityBlockingQueue(RequestQueue.java):用的是ReentrantLock同步锁,选择用ReentrantLock主要是其在高资源竞争下性能的高效显示锁灵活的操作;但如果是资源竞争不激烈的情况下表现不如synchronized,所以这也是为什么volley在下载大文件时表现不如意的原因之一

代码有点长,我们只挑重点看。首先在11行可以看到一个while(true)循环,说明缓存线程始终是在运行的,接着在第23行会尝试从缓存当中取出响应结果,如何为空的话则把这条请求加入到网络请求队列中,如果不为空的话再判断该缓存是否已过期,如果已经过期了则同样把这条请求加入到网络请求队列中,否则就认为不需要重发网络请求,直接使用缓存中的数据即可。之后会在第39行调用Request的parseNetworkResponse()方法来对数据进行解析,再往后就是将解析出来的数据进行回调了,这部分代码我们先跳过,因为它的逻辑和NetworkDispatcher后半部分的逻辑是基本相同的,那么我们等下合并在一起看就好了,先来看一下NetworkDispatcher中是怎么处理网络请求队列的,代码如下所示:
  1. public class NetworkDispatcher extends Thread {  
  2.     ……  
  3.     @Override  
  4.     public void run() {  
  5.         Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);  
  6.         Request<?> request;  
  7.         while (true) {  
  8.             try {  
  9.                 // Take a request from the queue.  
  10.                 request = mQueue.take();  
  11.             } catch (InterruptedException e) {  
  12.                 // We may have been interrupted because it was time to quit.  
  13.                 if (mQuit) {  
  14.                     return;  
  15.                 }  
  16.                 continue;  
  17.             }  
  18.             try {  
  19.                 request.addMarker("network-queue-take");  
  20.                 // If the request was cancelled already, do not perform the  
  21.                 // network request.  
  22.                 if (request.isCanceled()) {  
  23.                     request.finish("network-discard-cancelled");  
  24.                     continue;  
  25.                 }  
  26.                 addTrafficStatsTag(request);  
  27.                 // Perform the network request.  
  28.                 NetworkResponse networkResponse = mNetwork.performRequest(request);  
  29.                 request.addMarker("network-http-complete");  
  30.                 // If the server returned 304 AND we delivered a response already,  
  31.                 // we're done -- don't deliver a second identical response.  
  32.                 if (networkResponse.notModified && request.hasHadResponseDelivered()) {  
  33.                     request.finish("not-modified");  
  34.                     continue;  
  35.                 }  
  36.                 // Parse the response here on the worker thread.  
  37.                 Response<?> response = request.parseNetworkResponse(networkResponse);  
  38.                 request.addMarker("network-parse-complete");  
  39.                 // Write to cache if applicable.  
  40.                 // TODO: Only update cache metadata instead of entire record for 304s.  
  41.                 if (request.shouldCache() && response.cacheEntry != null) {  
  42.                     mCache.put(request.getCacheKey(), response.cacheEntry);  
  43.                     request.addMarker("network-cache-written");  
  44.                 }  
  45.                 // Post the response back.  
  46.                 request.markDelivered();  
  47.                 mDelivery.postResponse(request, response);  
  48.             } catch (VolleyError volleyError) {  
  49.                 parseAndDeliverNetworkError(request, volleyError);  
  50.             } catch (Exception e) {  
  51.                 VolleyLog.e(e, "Unhandled exception %s", e.toString());  
  52.                 mDelivery.postError(request, new VolleyError(e));  
  53.             }  
  54.         }  
  55.     }  
  56. }  
public class NetworkDispatcher extends Thread {
	……
    @Override
    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;
                }
                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);
            } catch (VolleyError volleyError) {
                parseAndDeliverNetworkError(request, volleyError);
            } catch (Exception e) {
                VolleyLog.e(e, "Unhandled exception %s", e.toString());
                mDelivery.postError(request, new VolleyError(e));
            }
        }
    }
}
同样地,在第7行我们看到了类似的while(true)循环,说明网络请求线程也是在不断运行的。在第28行的时候会调用Network的performRequest()方法来去发送网络请求,而Network是一个接口,这里具体的实现是BasicNetwork,我们来看下它的performRequest()方法,如下所示:
  1. public class BasicNetwork implements Network {  
  2.     ……  
  3.     @Override  
  4.     public NetworkResponse performRequest(Request<?> request) throws VolleyError {  
  5.         long requestStart = SystemClock.elapsedRealtime();  
  6.         while (true) {  
  7.             HttpResponse httpResponse = null;  
  8.             byte[] responseContents = null;  
  9.             Map<String, String> responseHeaders = new HashMap<String, String>();  
  10.             try {  
  11.                 // Gather headers.  
  12.                 Map<String, String> headers = new HashMap<String, String>();  
  13.                 addCacheHeaders(headers, request.getCacheEntry());  
  14.                 httpResponse = mHttpStack.performRequest(request, headers);  
  15.                 StatusLine statusLine = httpResponse.getStatusLine();  
  16.                 int statusCode = statusLine.getStatusCode();  
  17.                 responseHeaders = convertHeaders(httpResponse.getAllHeaders());  
  18.                 // Handle cache validation.  
  19.                 if (statusCode == HttpStatus.SC_NOT_MODIFIED) {  
  20.                     return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED,  
  21.                             request.getCacheEntry() == null ? null : request.getCacheEntry().data,  
  22.                             responseHeaders, true);  
  23.                 }  
  24.                 // Some responses such as 204s do not have content.  We must check.  
  25.                 if (httpResponse.getEntity() != null) {  
  26.                   responseContents = entityToBytes(httpResponse.getEntity());  
  27.                 } else {  
  28.                   // Add 0 byte response as a way of honestly representing a  
  29.                   // no-content request.  
  30.                   responseContents = new byte[0];  
  31.                 }  
  32.                 // if the request is slow, log it.  
  33.                 long requestLifetime = SystemClock.elapsedRealtime() - requestStart;  
  34.                 logSlowRequests(requestLifetime, request, responseContents, statusLine);  
  35.                 if (statusCode < 200 || statusCode > 299) {  
  36.                     throw new IOException();  
  37.                 }  
  38.                 return new NetworkResponse(statusCode, responseContents, responseHeaders, false);  
  39.             } catch (Exception e) {  
  40.                 ……  
  41.             }  
  42.         }  
  43.     }  
  44. }  
public class BasicNetwork implements Network {
	……
    @Override
    public NetworkResponse performRequest(Request<?> request) throws VolleyError {
        long requestStart = SystemClock.elapsedRealtime();
        while (true) {
            HttpResponse httpResponse = null;
            byte[] responseContents = null;
            Map<String, String> responseHeaders = new HashMap<String, String>();
            try {
                // Gather headers.
                Map<String, String> headers = new HashMap<String, String>();
                addCacheHeaders(headers, request.getCacheEntry());
                httpResponse = mHttpStack.performRequest(request, headers);
                StatusLine statusLine = httpResponse.getStatusLine();
                int statusCode = statusLine.getStatusCode();
                responseHeaders = convertHeaders(httpResponse.getAllHeaders());
                // Handle cache validation.
                if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
                    return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED,
                            request.getCacheEntry() == null ? null : request.getCacheEntry().data,
                            responseHeaders, true);
                }
                // Some responses such as 204s do not have content.  We must check.
                if (httpResponse.getEntity() != null) {
                  responseContents = entityToBytes(httpResponse.getEntity());
                } else {
                  // Add 0 byte response as a way of honestly representing a
                  // no-content request.
                  responseContents = new byte[0];
                }
                // if the request is slow, log it.
                long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
                logSlowRequests(requestLifetime, request, responseContents, statusLine);
                if (statusCode < 200 || statusCode > 299) {
                    throw new IOException();
                }
                return new NetworkResponse(statusCode, responseContents, responseHeaders, false);
            } catch (Exception e) {
                ……
            }
        }
    }
}

这段方法中大多都是一些网络请求细节方面的东西,我们并不需要太多关心,需要注意的是在第14行调用了HttpStack的performRequest()方法,这里的HttpStack就是在一开始调用newRequestQueue()方法是创建的实例,默认情况下如果系统版本号大于9就创建的HurlStack对象,否则创建HttpClientStack对象。前面已经说过,这两个对象的内部实际就是分别使用HttpURLConnection和HttpClient来发送网络请求的,我们就不再跟进去阅读了,之后会将服务器返回的数据组装成一个NetworkResponse对象进行返回。


在NetworkDispatcher中收到了NetworkResponse这个返回值后又会调用Request的parseNetworkResponse()方法来解析NetworkResponse中的数据,以及将数据写入到缓存,这个方法的实现是交给Request的子类来完成的,因为不同种类的Request解析的方式也肯定不同。还记得我们在上一篇文章中学习的自定义Request的方式吗?其中parseNetworkResponse()这个方法就是必须要重写的。


在解析完了NetworkResponse中的数据之后,又会调用ExecutorDelivery的postResponse()方法来回调解析出的数据,代码如下所示:

  1. public void postResponse(Request<?> request, Response<?> response, Runnable runnable) {  
  2.     request.markDelivered();  
  3.     request.addMarker("post-response");  
  4.     mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, runnable));  
  5. }  
public void postResponse(Request<?> request, Response<?> response, Runnable runnable) {
    request.markDelivered();
    request.addMarker("post-response");
    mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, runnable));
}
其中,在mResponsePoster的execute()方法中传入了一个ResponseDeliveryRunnable对象,就可以保证该对象中的run()方法就是在主线程当中运行的了,我们看下run()方法中的代码是什么样的:
  1. private class ResponseDeliveryRunnable implements Runnable {  
  2.     private final Request mRequest;  
  3.     private final Response mResponse;  
  4.     private final Runnable mRunnable;  
  5.   
  6.     public ResponseDeliveryRunnable(Request request, Response response, Runnable runnable) {  
  7.         mRequest = request;  
  8.         mResponse = response;  
  9.         mRunnable = runnable;  
  10.     }  
  11.   
  12.     @SuppressWarnings("unchecked")  
  13.     @Override  
  14.     public void run() {  
  15.         // If this request has canceled, finish it and don't deliver.  
  16.         if (mRequest.isCanceled()) {  
  17.             mRequest.finish("canceled-at-delivery");  
  18.             return;  
  19.         }  
  20.         // Deliver a normal response or error, depending.  
  21.         if (mResponse.isSuccess()) {  
  22.             mRequest.deliverResponse(mResponse.result);  
  23.         } else {  
  24.             mRequest.deliverError(mResponse.error);  
  25.         }  
  26.         // If this is an intermediate response, add a marker, otherwise we're done  
  27.         // and the request can be finished.  
  28.         if (mResponse.intermediate) {  
  29.             mRequest.addMarker("intermediate-response");  
  30.         } else {  
  31.             mRequest.finish("done");  
  32.         }  
  33.         // If we have been provided a post-delivery runnable, run it.  
  34.         if (mRunnable != null) {  
  35.             mRunnable.run();  
  36.         }  
  37.    }  
  38. }  
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();
        }
   }
}

代码虽然不多,但我们并不需要行行阅读,抓住重点看即可。其中在第22行调用了Request的deliverResponse()方法,有没有感觉很熟悉?没错,这个就是我们在自定义Request时需要重写的另外一个方法,每一条网络请求的响应都是回调到这个方法中,最后我们再在这个方法中将响应的数据回调到Response.Listener的onResponse()方法中就可以了。


好了,到这里我们就把Volley的完整执行流程全部梳理了一遍,你是不是已经感觉已经很清晰了呢?对了,还记得在文章一开始的那张流程图吗,刚才还不能理解,现在我们再来重新看下这张图:




其中蓝色部分代表主线程,绿色部分代表缓存线程,橙色部分代表网络线程。我们在主线程中调用RequestQueue的add()方法来添加一条网络请求,这条请求会先被加入到缓存队列当中,如果发现可以找到相应的缓存结果就直接读取缓存并解析,然后回调给主线程。如果在缓存中没有找到结果,则将这条请求加入到网络请求队列中,然后处理发送HTTP请求,解析响应结果,写入缓存,并回调主线程。


怎么样,是不是感觉现在理解这张图已经变得轻松简单了?好了,到此为止我们就把Volley的用法和源码全部学习完了,相信你已经对Volley非常熟悉并可以将它应用到实际项目当中了,那么Volley完全解析系列的文章到此结束,感谢大家有耐心看到最后。

针对于Volley的设计原理,RequestQueue相当于一个调度员,负责处理各种繁琐的事物,一个app只适合创建一个RequestQueue对象,否则会违背Volley“多执行少调度”的基本原则。

阅读更多

没有更多推荐了,返回首页