主要參考: http://blog.csdn.net/guolin_blog/article/details/17656437
工作流程圖:
volley_architecture.png
"
其中藍(lán)色部分代表主線程唆阿,綠色部分代表緩存線程弦撩,橙色部分代表網(wǎng)絡(luò)線程咽袜。我們在主線程中調(diào)用RequestQueue的add()方法來添加一條網(wǎng)絡(luò)請求,這條請求會先被加入到緩存隊列當(dāng)中歇由,如果發(fā)現(xiàn)可以找到相應(yīng)的緩存結(jié)果就直接讀取緩存并解析井联,然后回調(diào)給主線程疑枯。如果在緩存中沒有找到結(jié)果切省,則將這條請求加入到網(wǎng)絡(luò)請求隊列中最岗,然后處理發(fā)送HTTP請求,解析響應(yīng)結(jié)果朝捆,寫入緩存般渡,并回調(diào)主線程。
"
這里總結(jié)幾個技術(shù)要點:
Gingerbread之前芙盘, 底層網(wǎng)絡(luò)請求的實現(xiàn)使用HttpClient, Gingerbread之后驯用, 底層實現(xiàn)就開始使用HttpUrlConnection了, 因為Gingerbread之前的HttpUrlConnection不穩(wěn)定.
//Volley.java
public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
//File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
File cacheDir = new File(FeatureConfig.ROOT_CACHE_PATH_BASE, DEFAULT_CACHE_DIR);
String userAgent = "volley/0";
try {
String packageName = context.getPackageName();
PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
userAgent = packageName + "/" + info.versionCode;
} catch (Throwable e) {
}
if (stack == null) {
if (Build.VERSION.SDK_INT >= 9) {
//use httpUrlConnection
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;
}
RequestQueue.java
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();
//這里啟動一個Cache線程儒老, 不斷的從RequestQueue隊列里取元素.
// Create network dispatchers (and corresponding threads) up to the pool size.
//默認(rèn)創(chuàng)建4個Network線程蝴乔, 不斷的在自己的隊列里取元素, 執(zhí)行真正的網(wǎng)絡(luò)請求.
for (int i = 0; i < mDispatchers.length; i++) {
NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,
mCache, mDelivery);
mDispatchers[i] = networkDispatcher;
networkDispatcher.start();
}
}
CacheDispatcher是一個Thread, 它的run()方法驮樊, 是個死循環(huán).
public class CacheDispatcher extends Thread {
@Override
public void run() {
if (DEBUG) VolleyLog.v("start new dispatcher");
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
// Make a blocking call to initialize the cache.
mCache.initialize();
while (true) {
try {
// Get a request from the cache triage queue, blocking until
// at least one is available.
// 阻塞在這個, 從隊列里取元素.
final Request<?> request = mCacheQueue.take();
request.addMarker("cache-queue-take");
// If the request has been canceled, don't bother dispatching it.
if (request.isCanceled()) {
request.finish("cache-discard-canceled");
continue;
}
// 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;
}
...
// We have a cache hit; parse its data for delivery back to the request.
request.addMarker("cache-hit");
Response<?> response = null;
try {
response = request.parseNetworkResponse(
new NetworkResponse(entry.data, entry.responseHeaders));
} catch (Exception e) {
mDelivery.postError(request, new ParseError(e));
continue;
} catch (Error error) {
mDelivery.postError(request, new ParseError(error));
continue;
}
request.addMarker("cache-hit-parsed");
if (!entry.refreshNeeded()) {
// Completely unexpired cache hit. Just deliver the response.
mDelivery.postResponse(request, response);
} else {
// Soft-expired cache hit. We can deliver the cached response,
// but we need to also send the request to the network for
// refreshing.
request.addMarker("cache-hit-refresh-needed");
request.setCacheEntry(entry);
// Mark the response as intermediate.
response.intermediate = true;
// Post the intermediate response back to the user and have
// the delivery then forward the request along to the network.
mDelivery.postResponse(request, response, new Runnable() {
@Override
public void run() {
try {
mNetworkQueue.put(request);
} catch (InterruptedException e) {
// Not much we can do about this.
}
}
});
}
} catch (InterruptedException e) {
// We may have been interrupted because it was time to quit.
if (mQuit) {
return;
}
continue;
} catch (OutOfMemoryError error) {
if (mQuit) {
return;
}
continue;
}
}
}
NetworkDispatcher也是一個Thread, 它的run()方法薇正, 是個死循環(huán).
public class NetworkDispatcher extends Thread {
public void run() {
while(true) {
request = mQueue.take(); //阻塞在這里
NetworkResponse networkResponse = mNetwork.performRequest(request);
Response<?> response = request.parseNetworkResponse(networkResponse);
if (request.shouldCache() && response.cacheEntry != null) {
mCache.put(request.getCacheKey(), response.cacheEntry);
request.addMarker("network-cache-written");
}
}
}
Volley的總體框架還是非常的清晰的.
========DONE=========