Android网络框架很多,但是基于Google自己的volley,无疑是优秀的一款。

网络框架,无外乎解决一下几个问题,队列,缓存,图片异步加载,统一的网络请求和处理等。

一.Volley 队列 启动

Volley的队列,首先我们看队列的启动:com.android.volley.toolbox.Volley.java

 /**
* Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
*
* @param context A {@link Context} to use for creating the cache dir.
* @param stack An {@link HttpStack} to use for the network, or null for default.
* @return A started {@link RequestQueue} instance.
*/
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;
}

我们依次分析这个方法。这个方法是队列启动的代码。

开始就是获取缓存文件夹,以及userAgent 一些信息。

Build.VERSION.SDK_INT >= 9

会使用HTTPURLConnection作为网络请求,而老的版本就使用httpclient来处理。

关于这2者的区别,很多地方有介绍。HttpUrlConnection是HttpClient轻量级版本。

应该说性能更好,并且足够android平台使用了。

当然,也可以使用自己定义的HttpStack。

Network network = new BasicNetwork(stack);

Network对stack的进一步封装,然后创建队列和启动队列。

com/android/volley/RequestQueue.java:

    /**
* Starts the dispatchers in this queue.
*/
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();
}
}

启动队列,就是启动了一条cache thread 和4个 network thread。

然后分析CacheDispatcher 和NetworkDispatcher 这两个东东。

二:NetworkDispatcher

这一节我们分析网络请求,所以就忽略cache的部分,将在下一节分析:

public class NetworkDispatcher extends Thread

NetworkDispatcher是一个thread,可见network请求应该是从requestQueue队列中获取数据以后,已while(true)的形式不断的向服务器请求,

当requestQueue 为空时,线程讲block住,直到队列有数据,或者线程推出为止。

com/android/volley/NetworkDispatcher.java:

@Override
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
while (true) {
long startTimeMs = SystemClock.elapsedRealtime();
Request<?> request;
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默认是存在 PriorityBlockingQueue队列里面,

这个队列 可以解决2个问题。

1)线程间的同步

2)当队列为空时,take方法将会block住。

                // If the request was cancelled already, do not perform the
// network request.
if (request.isCanceled()) {
request.finish("network-discard-cancelled");
continue;
}

注释已经解释的很清楚了。

网络请求在这个进行:

NetworkResponse networkResponse = mNetwork.performRequest(request);
                // 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;
}

是否Modified。

Response<?> response = request.parseNetworkResponse(networkResponse);

把networkResponse转化成Response<?>.

接下去,就是判读是否需要cache,需要就保存此次请求结果。

然后就是分发这次的结果。

以上就是volley的一次网络请求的过程。

三:CacheDispatcher & Cache

首先是com/android/volley/RequestQueue.java

的add 方法。

/**
* Adds a Request to the dispatch queue.
* @param request The request to service
* @return The passed-in 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;
}
}

add

private final Set<Request<?>> mCurrentRequests 这个集合用于记录当前正在队列里面的request,此处的集合应该是所有的request。

request.setSequence(getSequenceNumber());

用于request的排序。

        if (!request.shouldCache()) {
mNetworkQueue.add(request);
return request;
}

request是否cache,如果否,讲直接放到network队列做请求操作。

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

如果cache队列里面已经有正在处理的request,就无需放入cache队列,直接等待返回结果时,会把所有重复的request加入cache。

下面我们分析cache线程的情况。

我们已经说过,request会在网络请求结束的时候,把可以cache的request放入cache库中。

com/android/volley/CacheDispatcher.java

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

通过cachekey,获取缓存的数据。没有的话,将有network dispatcher来处理。

接下来判断是否过期。

过期有2中状态,软过期,和completely 过期。

completely 过期。直接请求网络。

软过期,先response到前台,然后后台进行更新。

这个就是cache线程在干的事情。

再看看刚才response时如何产生cache数据的。

// Parse the response here on the worker thread.
Response<?> response = request.parseNetworkResponse(networkResponse);

可以看到居然是由每个request自己来决定如何产生cache数据。

Cache.Entry的获得将在:

com/android/volley/toolbox/HttpHeaderParser.java:

public static Cache.Entry parseCacheHeaders(NetworkResponse response)

中获得。这个方法时公共的,如何以后有自定义请求的时候,可以使用该方法。

自此一个volley的队列已经搭载启动了。

我们只需要把request放入requestQueue就可以了!

Volley源码分析(1)----Volley 队列的更多相关文章

  1. Volley源码分析(五)Volley源码总结篇

    volley关键的代码这里已经分析完了,下面梳理一下完整的Volley流程 Volley的使用从构造Request对象开始,Volley默认提供了四种request的实现,StringRequest, ...

  2. Android网络框架源码分析一---Volley

    转载自 http://www.jianshu.com/p/9e17727f31a1?utm_campaign=maleskine&utm_content=note&utm_medium ...

  3. Volley源码分析(2)----ImageLoader

    一:imageLoader 先来看看如何使用imageloader: public void showImg(View view){ ImageView imageView = (ImageView) ...

  4. Volley源码分析一

    Volley源码分析 虽然在2017年,volley已经是一个逐渐被淘汰的框架,但其代码短小精悍,网络架构设计巧妙,还是有很多值得学习的地方. 第一篇文章,分析了请求队列的代码,请求队列也是我们使用V ...

  5. Volley源码分析(一)RequestQueue分析

    Volley源码分析 虽然在2017年,volley已经是一个逐渐被淘汰的框架,但其代码短小精悍,网络架构设计巧妙,还是有很多值得学习的地方. 第一篇文章,分析了请求队列的代码,请求队列也是我们使用V ...

  6. Volley 源码分析

    Volley 源码分析 图片分析 要说源码分析,我们得先看一下官方的配图: 从这张图中我们可以了解到 volley 工作流程: 1.请求加入优先队列 2.从缓存调度器中查看是否存在该请求,如果有(没有 ...

  7. [Android]Volley源码分析(五)

    前面几篇通过源码分析了Volley是怎样进行请求调度及请求是如何被实际执行的,这篇最后来看下请求结果是如何交付给请求者的(一般是Android的UI主线程). 类图:

  8. Android Volley源码分析

    今天来顺手分析一下谷歌的volley http通信框架.首先从github上 下载volley的源码, 然后新建你自己的工程以后 选择import module 然后选择volley. 最后还需要更改 ...

  9. Volley源码分析

    取消请求的源码分析: public void cancelAll(RequestFilter filter) { synchronized (mCurrentRequests) { for (Requ ...

  10. Java并发系列[4]----AbstractQueuedSynchronizer源码分析之条件队列

    通过前面三篇的分析,我们深入了解了AbstractQueuedSynchronizer的内部结构和一些设计理念,知道了AbstractQueuedSynchronizer内部维护了一个同步状态和两个排 ...

随机推荐

  1. canvas剪裁图片并上传,前端一步到位,无需用到后端

    背景: 当前主流的图片剪裁主要有两种实现方式. 1:flash操作剪裁.2:利用js和dom操作剪裁. 目前看来这个剪裁主要还是先通过前端上传图片到服务器,然后前端操作后把一些坐标和大小数据传到后台, ...

  2. Solr搜索服务架构图

    来源:http://www.open-open.com/lib/view/open1400576900081.html

  3. Linux网络管理

    关于OSI七层模型.TCP五层模型.TCP的三次握手.HTTP协议.DNS解析等相关的网络基础知识请参考我整理的一篇博客:http://www.cnblogs.com/wxisme/p/4699049 ...

  4. LeetCode——Find Median from Data Stream

    Median is the middle value in an ordered integer list. If the size of the list is even, there is no ...

  5. hash函数为什么要选择对素数求余?

    常用的hash函数是选一个数m取模(余数),这个数在课本中推荐m是素数,但是经常见到选择m=2^n,因为对2^n求余数更快,并认为在key分布均匀的情况下,key%m也是在[0,m-1]区间均匀分布的 ...

  6. 一起Polyfill系列:Function.prototype.bind的四个阶段

    昨天边参考es5-shim边自己实现Function.prototype.bind,发现有不少以前忽视了的地方,这里就作为一个小总结吧. 一.Function.prototype.bind的作用 其实 ...

  7. SpringMVC基础——@ModelAttribute和@SessionAttribute

    一.@ModelAttribute 注解 对方法标注 @ModelAttribute 注解,在调用各个目标方法前都会去调用 @ModelAttribute 标记的注解.本质上来说,允许我们在调用目标方 ...

  8. 线段树 + 矩阵 --- ZOJ 3772 Calculate the Function

    Calculate the Function Problem's Link:   http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCod ...

  9. 【转】MSMQ消息队列安装

    一.Windows 7安装.管理消息队列1.安装消息队列   执行用户必须要有本地 Administrators 组中的成员身份,或等效身份.   具体步骤:    开始—>控制面板—>程 ...

  10. NFS客户端访问行为相关的几个参数解释

    soft / hard Determines the recovery behavior of the NFS client after an NFS request times out. If ne ...