android网络框架volley学习之Volley类

时间:2022-08-11 19:48:52

开题篇中最后提到了使用volley的三个步骤,这一篇就从步骤一的源码看起:建立RequestQueue对象。建立RequestQueue对象是同过Volley的静态方法建立的。

Volley类中,提供了三个生成RequestQueue的方法。两个利用默认的缓存目录生成RequestQueue的重载方法newRequestQueue,和一个用户自定义缓存目录的newRequestQueueInDisk方法。

下面看看源码
public class Volley {
private static final String DEFAULT_CACHE_DIR = "volley";//默认的缓存目录
//这里将context对象传入,保证了网络访问过程中activity销毁时,网络访问也会中断
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; //构造新的userAgent
} catch (NameNotFoundException e) {
}
//这里利用接口httpStack指向其实现此接口的类对象(HttpClientStack、HurlStack)
if (stack == null) {
if (Build.VERSION.SDK_INT >= 9) {
stack = new HurlStack();//根据httpURLconnection建立一个httpStack
} else {
stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));//根据httpclient建立httpstack
}
}
//这里利用接口network指向实现此接口的类对象BasicNetwork,构建Network对象network。
Network network = new BasicNetwork(stack);
/*利用匿名对象建立cache对象(多态的又一次应用,实际上引用的是DiskBasedCache对象)
*在这不难看出建立requestQueue对象的两个参数为cache缓存对象和network对象。其中缓存对象
*负责从缓存文件中来获取对应请求的相应response,而network则是通过其内部封装的HttpStack
*(HurlStack或者是HttpClientStack)来进行网络访问*/
RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
queue.start();//请求队列工作
return queue;
}

/**
* context
* dir sdcard's root dire
* null
* 用给定的文件目录建立缓存文件系统
* */
public static RequestQueue newRequestQueueInDisk(Context context, String dir, HttpStack stack) {
File cacheDir = new File(dir, 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 {
stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
}
}

Network network = new BasicNetwork(stack);

RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
queue.start();

return queue;
}

/**
* 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.
* @return A started {@link RequestQueue} instance.
*/
public static RequestQueue newRequestQueue(Context context) {
return newRequestQueue(context, null);
}
}