1.前言
Volley , 当我从第一次接触安卓开始就已经听过这个库的存在。
那时候我还不懂得什么的封装,每次都憨憨地从创建HttpURLConnection开始,然后open,然后getInputstream,然后再BufferedReader一步一步的将网页返回的数据变成一个String,再Gson解析成我要的数据来展示。
一直怀揣着对Volley的神秘感。对他的认识也就是道听途说来的,所以感觉还是需要深入一下。
所以写这篇文章也是为了加深一下自己的记忆。
因为自己水平非常有限,也不是什么大神,所以只能粗浅地分析一下,要是有错误,望各位批评指正。
这里附上一片专业的源代码分析,Volley 源码解析 - Trinea
2.RequestQueue
使用Volley的第一步:是创建一个RequestQueue队列。
RequestQueue mQueue = Volley.newRequestQueue(context);
OK,那我们来看看Volley.newRequestQueue()这个方法都做了什么。
附上Volley源代码:
public class Volley {
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, int maxDiskCacheBytes) {
return newRequestQueue(context, null, maxDiskCacheBytes);
}
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;
}
}
我们一步一步看,发现我们的一个参数的带参构造调用了两个参数的构造:
public static RequestQueue newRequestQueue(Context context, HttpStack stack)
{
return newRequestQueue(context, stack, -1);
}
两个参数的构造,调用了三个参数的构造:
public static RequestQueue newRequestQueue(Context context, int maxDiskCacheBytes) {
return newRequestQueue(context, null, maxDiskCacheBytes);
}
最终调用了,这个三个参数的构造方法:
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.