第一次接触到Volley,给我的印象就是用法很简洁,简单。上手很快,使用起来毫无压力。所以我决定弄清楚里面的源码是如何进行网络请求的,其实表面越简单的东西,其内部实现起来会越复杂,这次我主要从整体流程来分析。
Volley的使用:首先新建一个管理类,实现单例模式,获取Volley的网络请求队列
public static RequestManager getInstance(Context context) { if (mInstance == null) { synchronized(RequestManager.class) { if (mInstance == null) { mInstance = new RequestManager(context); } } } return mInstance; }复制代码
public RequestQueue getRequestQueue() { if (reqQueue == null){ synchronized(RequestManager.class) { if (reqQueue == null){ reqQueue = Volley.newRequestQueue(mContext); } } } return reqQueue;}复制代码
加入请求队列
public void addRequest(Request request, Object tag) { if (tag != null) { request.setTag(tag); } getRequestQueue().add(request); }复制代码
这时候使用起来就很简单了,只需要new一个Request对象,设置相应的回调,然后将Request加入到网络请求队列就行了。
StringRequest stringRequest = new StringRequest(url, new Listener() { @Override public void onResponse(String response) { // TODO 会调响应完成在这里做相应的处理 } }, new ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // TODO 访问出现错误处理 } }); RequestManager.getInstance(this).addRequest(stringRequest, this);复制代码
以上就是一般的Volley网络请求使用
现在开始我们的Volley源码解析
首先我们从获取网络请求队列开始Volley.newRequestQueue(mContext);
public static RequestQueue newRequestQueue(Context context) { return newRequestQueue(context, 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(), 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; if (maxDiskCacheBytes <= -1) { // No maximum size specified queue = new RequestQueue(new DiskBasedCache(cacheDir), network); } else { // Disk cache size specified queue = new RequestQueue(new DiskBasedCache(cacheDir, maxDiskCacheBytes), network); } queue.start(); return queue; }复制代码
可以看到这三个重载的方法,最终会调用 newRequestQueue(Context context, HttpStack stack, int maxDiskCacheBytes) { File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
这个方法。 这个方法主要做的事情就是,如果Android版本大于2.2的,stack就会使用HurlStack,否则使用HttpClientStack。 HurlStack是使用HttpURLConnection做网络访问,HttpClientStack是使用HttpClient网络访问。这两个有什么区别呢?可以看郭霖大神的 这篇文章。 然后新建对象Network network = new BasicNetwork(stack);
最后创建网络请求队列queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
,RequestQueue队列的构造方法也是一个重载方法,最终的构造方法进行赋值。其中threadPoolSize变量默认为开启4条线程。
public RequestQueue(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery) { mCache = cache; mNetwork = network; mDispatchers = new NetworkDispatcher[threadPoolSize]; mDelivery = delivery; }复制代码
我们回到 newRequestQueue(Context context, HttpStack stack, int maxDiskCacheBytes) { File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
中,看到此方法最后会调用queue.start();
,我们看看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(); } }复制代码
从上面方法中可以看出,首先调用stop()
方法来确保所有当前的正在运行的网络调度都停止,然后创建一个新的缓存分发对象CacheDispatcher,CacheDispatcher是一个继承Thread的线程,然后开始执行CacheDispatcher,看看CacheDispatcher所做的事情,主要看run()
方法
@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(); Request request; while (true) { // release previous request object to avoid leaking request object when mQueue is drained. request = null; try { // Take a request from the queue. request = mCacheQueue.take(); } catch (InterruptedException e) { // We may have been interrupted because it was time to quit. if (mQuit) { return; } continue; } try { 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. final Request finalRequest = request; mDelivery.postResponse(request, response, new Runnable() { @Override public void run() { try { mNetworkQueue.put(finalRequest); } catch (InterruptedException e) { // Not much we can do about this. } } }); } } catch (Exception e) { VolleyLog.e(e, "Unhandled exception %s", e.toString()); } } }复制代码
我们看run()
方法的主要做的事情:首先拿出队列头request = mCacheQueue.take();
,然后设置标志request.addMarker("cache-queue-take");
,接着从缓存中取出响应结果,如果响应结果为空if (entry == null)
或者缓存失效if (entry.isExpired())
,都会加入到网络请求队列中mNetworkQueue.put(request);
,调用网络请求获取结果。如果缓存线程中取得结果会调用ResponseDelivery的postResponse方法。 而ResponseDelivery的实现就是RequestQueue构造方法new出来的ExecutorDelivery对象,我们看下ExecutorDelivery中的postResponse方法的实现。
@Override public void postResponse(Request request, Response response) { postResponse(request, response, null); } @Override public void postResponse(Request request, Response response, Runnable runnable) { request.markDelivered(); request.addMarker("post-response"); mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, runnable)); }复制代码
public ExecutorDelivery(final Handler handler) { // Make an Executor that just wraps the handler. mResponsePoster = new Executor() { @Override public void execute(Runnable command) { handler.post(command); } }; }复制代码
从ExecutorDelivery可以看出,其主要做的事情是:将结果发送到主线程。再看下ResponseDeliveryRunnable
做了什么操作
@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(); } }复制代码
上面的run方法中最重要的一句是
if (mResponse.isSuccess()) { mRequest.deliverResponse(mResponse.result); } else { mRequest.deliverError(mResponse.error); }复制代码
如果响应成功的话就会调用Request的deliverResponse方法,如果错误就会调用deliverError方法,而这个Request方法就是我们使用时new请求对象,而文章开头我们使用的时StringRequest这个对象,那么我们看看StringRequest的deliverResponse方法。
@Override protected void deliverResponse(String response) { if (mListener != null) { mListener.onResponse(response); } }复制代码
deliverResponse方法的mListener对象就是我们使用时传进来的回调接口,所以最终结果我们可以在设置回调的onResponse方法中使用。
分析到这里我们就知道了Volley的调用流程了,就知道为什么我们只是简单的new一个请求对象然后设置回调,并把请求对象加入请求队列就可以完成整个网络请求了。
接下来我们在回看queue.start()
的网络请求。主要看下面的语句
for (int i = 0; i < mDispatchers.length; i++) { NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork, mCache, mDelivery); mDispatchers[i] = networkDispatcher; networkDispatcher.start(); }复制代码
前面我们知道默认的线程数设置时4,所以这里回循环4次,主要还是看回NetworkDispatcher类,同样NetworkDispatcher也是继承Thread的线程类。 主要看run()
方法
@Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); Request request; while (true) { long startTimeMs = SystemClock.elapsedRealtime(); // release previous request object to avoid leaking request object when mQueue is drained. request = null; 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) { volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs); parseAndDeliverNetworkError(request, volleyError); } catch (Exception e) { VolleyLog.e(e, "Unhandled exception %s", e.toString()); VolleyError volleyError = new VolleyError(e); volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs); mDelivery.postError(request, volleyError); } } }复制代码
run():首先回取出队列头request = mQueue.take();
获取request,接着看网络请求最最主要的一句NetworkResponse networkResponse = mNetwork.performRequest(request);
这一句呢主要是网络访问,获取得到结果。从RequestQueue的newRequestQueue方法中我们可以知道:如果Android版本大于2.2的会使用HttpURLConnection进行网络访问,否则使用HttpClient。 网络访问完成之后会对响应结果进行解析Response<?> response = request.parseNetworkResponse(networkResponse);
,接着之后将结果放到缓存线程mCache.put(request.getCacheKey(), response.cacheEntry);
,跟缓存线程一样 最终调用mDelivery.postResponse(request, response);
将结果回调。
至此,整个volley解剖完成,大家应该也知道整体调用流程了。如果还有不明白的,可以看下volley官方给出来的这张图,结合我的分析就一目了然了。
该文章是我看了好几天的源码分析得来的,哪里分析得不好请大家指出来,相互学习。网上也有很多分析volley的文章,如有雷同,纯属偶合。