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. [python]爬代理ip v2.0(未完待续)

    爬代理ip 所有的代码都放到了我的github上面, HTTP代理常识 HTTP代理按匿名度可分为透明代理.匿名代理和高度匿名代理. 特别感谢:勤奋的小孩 在评论中指出我文章中的错误. REMOTE_ ...

  2. [python]非常小的下载图片脚本(非通用)

    说在最前面:这不是一个十分通用的下载图片脚本,只是根据我的一个小问题,为了减少我的重复性工作写的脚本. 问题 起因:我的这篇博文什么是真正的程序员浏览量超过了4000+. 问题来了:里面的图片我都是用 ...

  3. Android 定时器

    Andorid定时器封装类 public class TimerUtil { private static final String TAG = "TimerUtil"; priv ...

  4. fis3使用环境

    1.全局安装nodejs 2.安装http-server npm install http-server -g 3.安装fis3 npm install -g fis3 如要限制版本号写法是:npm ...

  5. Android 学习笔记之如何实现简单相机功能

    PS:看来算法和数据结构还是非常有用的,以后每天都练习两道算法题目...这次忘了对代码进行折叠了..导致篇幅过长... 学习内容: 1.Android如何实现相机功能... 2.如何实现音频的录制.. ...

  6. DIV+CSS常用网页布局技巧!

    以下是我整理的DIV+CSS常用网页布局技巧,仅供学习与参考! 第一种布局:左边固定宽度,右边自适应宽度 HTML Markup <div id="left">Left ...

  7. JavaScript--DOM修改元素的属性

    一旦你获得了要修改的元素,可以有2种方式,来读取和修改它的属性:一种老的方式(它被更多的用户代理所支持)和一种新的DOM方法的方式.老的和新的用户代理都允许你以对象属性的方式获取和设置元素的属性. 先 ...

  8. JS实现注销功能

    JS实现注销功能,代码如下: <script> window.history.forward(1); </script> 这个代码的用法就是: 比如,我们此时有两个页面:Log ...

  9. 【C#进阶系列】02 PE文件,程序集,托管模块,元数据——还是那个Hello world

    好了,还是这张图,还是一样的Hello world. 因为本章其实很多都是讲一些命令行编译啊什么鬼的配置类的东西,要用的时候直接百度或者回头查书就可以了, 所以了解一下也就行了,也没有记录下来,接下来 ...

  10. 重新想象 Windows 8.1 Store Apps (88) - 通信的新特性: 新的 HttpClient

    [源码下载] 重新想象 Windows 8.1 Store Apps (88) - 通信的新特性: 新的 HttpClient 作者:webabcd 介绍重新想象 Windows 8.1 Store ...