您好,欢迎访问一九零五行业门户网

Android开发—Volley源码的详细分析

0. 前言  
其实写这篇文章只为一个目的,虽然volley用起来很爽,但是面试官问你人家内部是怎么实现呢,没看过源码的话,在面试官眼里你和一个拿着一本volley使用手册的高中生没啥区别。还是那句话说得好,会用一回事,深入理解又是另一回事了。
1.  volley源码解析
1.1  volley入口
volley首先获取到的是requestqueue实例。源码中则直接调用了newrequestqueue方法。
public static requestqueue newrequestqueue(context context) { return newrequestqueue(context, null); } 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; }
从上面源码中可以看到,判断传入的stack为空,则根据系统版本去创建一个httpstack对象,大于等于9的,则创建一个hurlstack的实例(内部使用httpurlconnection),否则就创建一个httpclientstack的实例(内部使用httpclient)。之所以这样做是因为:
(1)httpurlconnection在小于9的版本中存在调用imputstream.close()会导致连接池失败的bug,相对来说httpclient在小于9的系统版本中有较少的bug。
(2)而在大于等于9的版本中,httpurlconnection的实现有更多的优点,api更简单,体积更小,有压缩功能以及4.0以后加入的缓存机制(如本地缓存、304缓存、服务器缓存)。
创建好了httpstack之后将其作为参数创建了一个network对象,接着又根据network对象创建了一个requestqueue对象,并调用它的start()方法进行启动,然后将该实例返回。
1.2 requestqueue.start()
public void start() { stop(); mcachedispatcher = new cachedispatcher(mcachequeue, mnetworkqueue, mcache, mdelivery); mcachedispatcher.start(); for (int i = 0; i < mdispatchers.length; i++) { //默认循环4次 networkdispatcher networkdispatcher = new networkdispatcher(mnetworkqueue, mnetwork, mcache, mdelivery); mdispatchers[i] = networkdispatcher; networkdispatcher.start(); } }
这里cachedispatcher和networkdispatcher都是继承自thread的,也就是说当调用了volley.newrequestqueue(context)之后,一个缓存线程和四个网络请求线程会一直在后台运行,并等待网络请求的到来。
1.3 requestqueue.add()
既然上面已经迫不及待等待网络请求的到来了,那么是时候将我们的request添加进队列了。
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行的时候会判断当前的请求是否可以缓存,默认情况下是可以缓存的,除非主动调用了request的setshouldcache(false)方法来不允许其进行缓存。因此默认情况下会将该请求加入到缓存队列,否则直接加入网络请求队列。下面看看缓存线程中的run方法。
1.4 cachedispatcher中的run()
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; } } }
可以看到while(true)的循环说明缓存线程始终是在运行,接着会尝试从缓存当中取出响应结果,如何为空则把这条请求加入到网络请求队列中,否则判断该缓存是否已过期,如果已经过期那么肯定还是同上处理,没有过期就直接使用缓存中的数据。
之后就是和网络请求队列请求到数据后一样的数据解析逻辑以及解析结果回调逻辑。
1.5 networkdispatcher中的run()
接下来就是分析正常情况下,没有缓存的情况下,网络请求是什么样子的。直接看网络请求线程中的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; } 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)); } } } }
while(true)循环说明网络请求线程也是在不断运行的。在第25行可以看到调用了network的performrequest()方法发送网络请求,而network是一个接口,这里具体的实现是basicnetwork,我们来看下它的performrequest()方法,如下所示:
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) { …… } } }
里面除去一些网络请求的细节,看到在第11行调用了httpstack的performrequest()方法,这里的httpstack就是在一开始调用newrequestqueue()方法是创建的实例,之后会将服务器返回的数据组装成一个networkresponse对象进行返回。
收到了networkresponse这个返回值后会调用request的parsenetworkresponse()方法来解析networkresponse中的数据,以及将数据写入到缓存,这个方法的实现是交给request的子类来完成的,因为不同种类的request解析的方式也肯定不同。在解析完了networkresponse中的数据之后,又会调用executordelivery的postresponse()方法来回调解析出的数据,代码如下所示:
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); } }; } # postresponse方法 public void postresponse(request<?> request, response<?> response, runnable runnable) { request.markdelivered(); request.addmarker("post-response"); mresponseposter.execute(new responsedeliveryrunnable(request, response, runnable)); }
在该类的构造函数中传入了一个主线程创建的handler,最后一行代码在mresponseposter的execute()方法中传入一个responsedeliveryrunnable对象,这样就可以通过handler.post(runnable)切换到了主线程。我们继续看下这个runnable中的run()方法中的代码是什么样的:
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()方法,这个和parsenetworkresponse()方法一样都是我们在自定义request时需要重写的方法,每一条网络请求的响应都是回调到这个方法中,再在这个方法中将响应的数据回调到listener的onresponse()方法中,即我们创建request时传入的那个listener。
以上就是android开发—volley源码的详细分析的详细内容。
其它类似信息

推荐信息