当前位置: 移动技术网 > IT编程>移动开发>Android > 深入解读Android的Volley库的功能结构

深入解读Android的Volley库的功能结构

2019年07月24日  | 移动技术网IT编程  | 我要评论

印度制造溃不成军,斗战神牛魔狂暴领域,bm跨国企业人力资源共享

volley 是一个 http 库,它能够帮助 android app 更方便地执行网络操作,最重要的是,它更快速高效。我们可以通过开源的 aosp 仓库获取到 volley 。
volley 有如下的优点:

  • 自动调度网络请求。
  • 高并发网络连接。
  • 通过标准的 http cache coherence(高速缓存一致性)缓存磁盘和内存透明的响应。
  • 支持指定请求的优先级。
  • 撤销请求 api。我们可以取消单个请求,或者指定取消请求队列中的一个区域。
  • 框架容易被定制,例如,定制重试或者回退功能。
  • 强大的指令(strong ordering)可以使得异步加载网络数据并正确地显示到 ui 的操作更加简单。
  • 包含了调试与追踪工具。

volley 擅长执行用来显示 ui 的 rpc 类型操作,例如获取搜索结果的数据。它轻松的整合了任何协议,并输出操作结果的数据,可以是原始的字符串,也可以是图片,或者是 json。通过提供内置的我们可能使用到的功能,volley 可以使得我们免去重复编写样板代码,使我们可以把关注点放在 app 的功能逻辑上。
volley 不适合用来下载大的数据文件。因为 volley 会保持在解析的过程中所有的响应。对于下载大量的数据操作,请考虑使用 downloadmanager。
volley 框架的核心代码是托管在 aosp 仓库的 frameworks/volley 中,相关的工具放在 toolbox 下。把 volley 添加到项目中最简便的方法是 clone 仓库,然后把它设置为一个 library project:
通过下面的命令来clone仓库:

git clone https://android.googlesource.com/platform/frameworks/volley

以一个 android library project 的方式导入下载的源代码到你的项目中。

下面我们就来剖析一下volley的java源码:

requestqueue
使用 volley 的时候,需要先获得一个 requestqueue 对象。它用于添加各种请求任务,通常是调用 volly.newrequestqueue() 方法获取一个默认的 requestqueue。我们就从这个方法开始,下面是它的源码:

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 {
 // 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;
}

newrequestqueue(context) 调用了它的重载方法 newrequestqueue(context,null)。在这个方法中,先是通过 context 获得了缓存目录并且构建了 useragent 信息。接着判断 stack 是否为空,从上面的调用可以知道,默认情况下 stack==null, 所以新建一个 stack 对象。根据系统版本不同,在版本号大于 9 时,stack 为 hurlstack,否则为 httpclientstack。它们的区别是,hurlstack 使用 httpurlconnection 进行网络通信,而 httpclientstack 使用 httpclient。有了 stack 后,用它创建了一个 basicnetwork 对象,可以猜到它是用来处理网络请求任务的。紧接着,新建了一个 requestqueue,这也是最终返回给我们的请求队列。这个 requestqueue 接受两个参数,第一个是 diskbasedcache 对象,从名字就可以看出这是用于硬盘缓存的,并且缓存目录就是方法一开始取得的 cachedir;第二个参数是刚刚创建的 network 对象。最后调用 queue.start() 启动请求队列。

在分析 start() 之前,先来了解一下 requestqueue 一些关键的内部变量以及构造方法:

//重复的请求将加入这个集合
private final map<string, queue<request>> mwaitingrequests =
 new hashmap<string, queue<request>>();
//所有正在处理的请求任务的集合 
private final set<request> mcurrentrequests = new hashset<request>();
//缓存任务的队列
private final priorityblockingqueue<request> mcachequeue =
 new priorityblockingqueue<request>();
//网络请求队列
private final priorityblockingqueue<request> mnetworkqueue =
 new priorityblockingqueue<request>();
//默认线程池大小
private static final int default_network_thread_pool_size = 4;
//用于响应数据的存储与获取
private final cache mcache;
//用于网络请求
private final network mnetwork;
//用于分发响应数据
private final responsedelivery mdelivery;
//网络请求调度
private networkdispatcher[] mdispatchers;
//缓存调度
private cachedispatcher mcachedispatcher;

public requestqueue(cache cache, network network) {
 this(cache, network, default_network_thread_pool_size);
}
public requestqueue(cache cache, network network, int threadpoolsize) {
 this(cache, network, threadpoolsize,
 new executordelivery(new handler(looper.getmainlooper())));
}
public requestqueue(cache cache, network network, int threadpoolsize,
 responsedelivery delivery) {
 mcache = cache;
 mnetwork = network;
 mdispatchers = new networkdispatcher[threadpoolsize];
 mdelivery = delivery;
}

requestqueue 有多个构造方法,最终都会调用最后一个。在这个方法中,mcache 和 mnetwork 分别设置为 newrequestqueue 中传来的 diskbasedcache 和 basicnetwork。mdispatchers 为网络请求调度器的数组,默认大小 4 (default_network_thread_pool_size)。mdelivery 设置为 new executordelivery(new handler(looper.getmainlooper())),它用于响应数据的传递,后面会具体介绍。可以看出,其实我们可以自己定制一个 requestqueue 而不一定要用默认的 newrequestqueue。

下面就来看看 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();
 }
}

代码比较简单,就做了两件事。第一,创建并且启动一个 cachedispatcher。第二,创建并启动四个 networkdispatcher。所谓的启动请求队列就是把任务交给缓存调度器和网络请求调度器处理。

这里还有个问题,请求任务是怎么加入请求队列的?其实就是调用了 add() 方法。现在看看它内部怎么处理的:

public request add(request 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;
 }
}

这个方法的代码稍微有点长,但逻辑并不复杂。首先把这个任务加入 mcurrentrequests,然后判断是否需要缓存,不需要的话就直接加入网络请求任务队列 mnetworkqueue 然后返回。默认所有任务都需要缓存,可以调用 setshouldcache(boolean shouldcache) 来更改设置。所有需要缓存的都会加入缓存任务队列 mcachequeue。不过先要判断 mwaitingrequests 是不是已经有了,避免重复的请求。

dispatcher
requestqueue 调用 start() 之后,请求任务就被交给 cachedispatcher 和 networkdispatcher 处理了。它们都继承自 thread,其实就是后台工作线程,分别负责从缓存和网络获取数据。

cachedispatcher
cachedispatcher 不断从 mcachequeue 取出任务处理,下面是它的 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;
 }
 }
}

首先是调用 mcache.initialize() 初始化缓存,然后是一个 while(true) 死循环。在循环中,取出缓存队列的任务。先判断任务是否取消,如果是就执行 request.finish("cache-discard-canceled") 然后跳过下面的代码重新开始循环,否则从缓存中找这个任务是否有缓存数据。如果缓存数据不存在,把任务加入网络请求队列,并且跳过下面的代码重新开始循环。如果找到了缓存,就判断是否过期,过期的还是要加入网络请求队列,否则调用 request 的parsenetworkresponse 解析响应数据。最后一步是判断缓存数据的新鲜度,不需要刷新新鲜度的直接调用 mdelivery.postresponse(request, response) 传递响应数据,否则依然要加入 mnetworkqueue 进行新鲜度验证。

上面的代码逻辑其实不是很复杂,但描述起来比较绕,下面这张图可以帮助理解:

201656145935002.jpg (800×600)

networkdispatcher
cachedispatcher 从缓存中寻找任务的响应数据,如果任务没有缓存或者缓存失效就要交给 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));
 }
 }
}

可以看出,run() 方法里面依然是个无限循环。从队列中取出一个任务,然后判断任务是否取消。如果没有取消就调用 mnetwork.performrequest(request) 获取响应数据。如果数据是 304 响应并且已经有这个任务的数据传递,说明这是 cachedispatcher 中验证新鲜度的请求并且不需要刷新新鲜度,所以跳过下面的代码重新开始循环。否则继续下一步,解析响应数据,看看数据是不是要缓存。最后调用 mdelivery.postresponse(request, response) 传递响应数据。下面这张图展示了这个方法的流程:

201656150017770.jpg (800×600)

delivery
在 cachedispatcher 和 networkdispatcher 中,获得任务的数据之后都是通过 mdelivery.postresponse(request, response) 传递数据。我们知道 dispatcher 是另开的线程,所以必须把它们获取的数据通过某种方法传递到主线程,来看看 deliver 是怎么做的。
mdelivery 的类型为 executordelivery,下面是它的 postresponse 方法源码:

public void postresponse(request<?> request, response<?> response) {
 postresponse(request, response, null);
}
public void postresponse(request<?> request, response<?> response, runnable runnable) {
 request.markdelivered();
 request.addmarker("post-response");
 mresponseposter.execute(new responsedeliveryrunnable(request, response, runnable));
}

从上面的代码可以看出,最终是通过调用 mresponseposter.execute(new responsedeliveryrunnable(request, response, runnable)) 进行数据传递。这里的 mresponseposter 是一个 executor 对象。

private final executor mresponseposter;

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);
 }
 };

executor 是线程池框架接口,里面只有一个 execute() 方法,mresponseposter 的这个方法实现为用 handler 传递 runnable 对象。而在 postresponse 方法中,request 和 response 被封装为 responsedeliveryrunnable, 它正是一个 runnable 对象。所以响应数据就是通过 handler 传递的,那么这个 handler 是哪里来的?其实在介绍 requestqueue 的时候已经提到了:mdelivery 设置为 new executordelivery(new handler(looper.getmainlooper())),这个 handler 便是 new handler(looper.getmainlooper()),是与主线程的消息循环连接在一起的,这样数据便成功传递到主线程了。

总结
volley 的基本工作原理就是这样,用一张图总结一下它的运行流程:

201656150034469.jpg (800×600)

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网