1.普及知识
PriorityBlockingQueue类是JDK提供的优先级队列 本身是线程安全的,通过take()方法取队列里的值,这个方法有个特点,如果没有取到值就一直阻塞在那里。Volley里就是在无限循环中从此队列取值,没有取到就一直阻塞,当请求比如StringRequest加到队列中时,循环才走的去
下面以StringRequest为例分析源码
2.先看看怎么使用
RequestQueue mQueue = Volley.newRequestQueue(context);
StringRequest stringRequest = new StringRequest(Method.POST,"http://www.baidu.com",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
mQueue.add(stringRequest);
3.再看看都做了些什么
3.1实例化RequestQueue
RequestQueue mQueue = Volley.newRequestQueue(context);
最终调用方法
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(new BasicUrlRewriter(), userAgent);
} 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), new BasicUrlRewriter());
}
}
Network network = new BasicNetwork(stack);
RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
queue.start();
return queue;
}
其他的先不管,先看这两个
RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
queue.start();
在RequestQueue的构造方法中
public RequestQueue(Cache cache, Network network, int threadPoolSize,
ResponseDelivery delivery) {
mCache = cache;
mNetwork = network;
mDispatchers = new NetworkDispatcher[threadPoolSize];
mDelivery = delivery;
}
这里主要关注
mDispatchers = new NetworkDispatcher[threadPoolSize];
mDelivery = delivery;
new了有4个NetworkDispatcher的数组,mDelivery是等到请求成功后将请求的结果通过listerner回调的。
然后queue.start();
3.2调用RequestQueue的start方法
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();
}
}
这里面开了一个CacheDispatcher线程和4个NetworkDispatcher线程。由于上面说了,我们先只考虑post请求,post请求默认是不会被缓存的,所以缓存线程CacheDispatcher我们先不管它,我们看NetworkDispatcher线程的run方法
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Request request;
while (true) {
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;
}
......
}
线程开启后,进入while(true)循环,由于一开始还没有请求,会一直阻塞在request = mQueue.take();好了,这块先只看到这里。
3.3将request加入到queue后做了什么
mQueue.add(stringRequest);
public Request add(Request 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;
}
......
}
主要将request(这里就是我们实例化的StringRequest)加入到mCurrentRequests和mNetworkQueue(说好的,先不看缓存,那么shouldCache()返回false,下面直接return了request)。
而实例化NetworkDispatcher的时候就看到mNetworkQueue作为参数传进去了,NetworkDispatcher的run方法中request = mQueue.take();中的mQueue就是mNetworkQueue。所以等于我们把请求加到mNetworkQueue中,4个NetworkDispatcher线程在while(true)循环中不断的取数据。同样是NetworkDispatcher线程的run方法,看看取到数据后干了什么
3.4解析数据
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);
先调用了mNetwork的performRequest方法,这里先不细细研究。mNetwork是实例化RequestQueue时传入的BasiNetwork,它的performRequest方法就是将请求处理后封装为NetworkResponce返回回来。
再调用了request(StringRequest)的parseNetworkResponse方法,
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
此方法中,将NetworkResponse转化为Response<String>(因为是StringRequest)。
3.5将解析好的数据在主线程中回调给listener
最后调用mDelivery的postResponse方法。从RequestQueue的构造方法中可以找到,传入的mDelivery就是ExecutorDelivery。那么就看一下ExecutorDelivery的postResponse方法(注意:,传入ExecutorDelivery时,ExecutorDelivery的构造方法中的Handle是和主线程的Looper相关联的
new ExecutorDelivery(new Handler(Looper.getMainLooper()))
)
public void postResponse(Request<?> request, Response<?> response, Runnable runnable) {
request.markDelivered();
request.addMarker("post-response");
mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, runnable));
}
主要执行了mResponsePoster的execute方法,来看看mResponsePoster是什么
public ExecutorDelivery(final Handler handler) {
// Make an Executor that just wraps the handler.
mResponsePoster = new Executor() {
@Override
public void execute(Runnable command) {
handler.post(command);
}
};
}
最终execute方法里,执行了handle的post方法,不用说ResponseDeliveryRunnable肯定就是Runnable的继承类咯,而且会在主线程中调用它的run方法。来看一下ResponseDeliveryRunnable的run方法
public void run() {
// If this request has canceled, finish it and don't deliver.
if (mRequest.isCanceled()) {
mRequest.finish("canceled-at-delivery");
return;
}
// Deliver a normal response or error, depending.
if (mResponse.isSuccess()) {
mRequest.deliverResponse(mResponse.result);
} else {
mRequest.deliverError(mResponse.error);
}
// If this is an intermediate response, add a marker, otherwise we're done
// and the request can be finished.
if (mResponse.intermediate) {
mRequest.addMarker("intermediate-response");
} else {
mRequest.finish("done");
}
// If we have been provided a post-delivery runnable, run it.
if (mRunnable != null) {
mRunnable.run();
}
}
请求成功的话调用mRequest.deliverResponse(mResponse.result);否则调用mRequest.deliverError(mResponse.error);
请求成功,StringRequest里的deliverResponse方法
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
可见将返回的String交给listener回调了。
请求失败,Request的deliverError方法(StringRequest没有重写deliverError方法,直接看父类)
public void deliverError(VolleyError error) {
if (mErrorListener != null) {
mErrorListener.onErrorResponse(error);
}
}
为什么会这样?
因为请求成功时,StringRequest返回的是String,JsonRequest返回的是Json,所以请求成功的方法子类需要重写,而请求失败的话返回的参数就是VolleyError,所有子类都一样,不需要重写。
写到这里,Volley的大致流程应该有个清楚的概念了吧