我们使用Volley时首先会调用这条语句
RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
其中返回值为RequestQueue。调用的是volley类里面的静态方法。
首先来看Volley类
它有3个重载的静态方法。
第一个
public static RequestQueue newRequestQueue(Context context) {
return newRequestQueue(context, (BaseHttpStack) null);
}
return newRequestQueue(context, (BaseHttpStack) null); 将会调用第二个重载的方法
public static RequestQueue newRequestQueue(Context context, BaseHttpStack stack) {
BasicNetwork network;
if (stack == null) {
if (Build.VERSION.SDK_INT >= 9) {
network = new BasicNetwork(new HurlStack());
} else {
// Prior to Gingerbread, HttpUrlConnection was unreliable.
// See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
// At some point in the future we'll move our minSdkVersion past Froyo and can
// delete this fallback (along with all Apache HTTP code).
String userAgent = "volley/0";
try {
String packageName = context.getPackageName();
PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
userAgent = packageName + "/" + info.versionCode;
} catch (NameNotFoundException e) {
}
network = new BasicNetwork(
new HttpClientStack(AndroidHttpClient.newInstance(userAgent)));
}
} else {
network = new BasicNetwork(stack);
}
return newRequestQueue(context, network);
}
这段代码将会初始化一个BasicNetwork,之后会分析这个类
return newRequestQueue(context, network); 将会调用第三个重载方法
private static RequestQueue newRequestQueue(Context context, Network network) {
File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
queue.start();
return queue;
}
这段代码将会创建一个RequestQueue对象, queue.start();将会使CacheDispatcher、NetworkDispatcher开启线程。这样初始化工作就做好了,RequestQueue队列将会等待队列有请求发出然后进行请求。那么是怎么实现的呢?接下来来看RequestQueue类。
网友评论