簡介
- 關於Volley封裝性跟實用性是毋庸置疑的,本篇文章是爭對上一篇文章
Volley – 基本用法做出比較詳細的過程分析,分析Volley請求的流程,緩存的策略,工作線程的執行分配,接口回調的機制,代碼的封裝等相關進行分析,涉及到Volley的相關類有Request、Response、NetworkDispatcher、CacheDispatcher、Cache、Network等。 - 本篇文章通過提問方式展示上面提及的相關知識點,你可以當成一次複習,也可以當成一次面試,ヽ(^0^)ノ一次不正式的面試,哈哈,接下來開始吧。
- 現在還寫了關於Volley的圖片處理源碼分析,分析關於Volley對圖片的壓縮,請求的處理等Volley – 圖片處理方式源碼分析
問題
- 對於請求結果(包括錯誤結果),是怎麼被傳遞到UI線程,也就是說怎麼回調到了Response.Listener、Response.ErrorListener接口的。
- 請求(Request)是如何得到結果(Response)的。
- Volley緩存機制
- ……
解答問題一:請求結果怎麼回調到Response.Listener、Response.ErrorListener接口
咚,看到ResponseDelivery源碼
public interface ResponseDelivery {
/**
* Parses a response from the network or cache and delivers it.
*/
public void postResponse(Request<?> request, Response<?> response);
/**
* Parses a response from the network or cache and delivers it. The provided
* Runnable will be executed after delivery.
*/
public void postResponse(Request<?> request, Response<?> response, Runnable runnable);
/**
* Posts an error for the given request.
*/
public void postError(Request<?> request, VolleyError error);
}
發現它是一個接口,用於傳送結果的
看一下它的子類ExecutorDelivery
/**
* Delivers responses and errors.
*/
public class ExecutorDelivery implements ResponseDelivery {
/** Used for posting responses, typically to the main thread. */
private final Executor mResponsePoster;
/**
* Creates a new response delivery interface.
* @param handler {@link Handler} to post responses on
*/
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);
}
};
}
/**
* Creates a new response delivery interface, mockable version
* for testing.
* @param executor For running delivery tasks
*/
public ExecutorDelivery(Executor executor) {
mResponsePoster = executor;
}
@Override
public void postResponse(Request<?> request, Response<?> response) {
postResponse(request, response, null);
}
@Override
public void postResponse(Request<?> request, Response<?> response, Runnable runnable) {
request.markDelivered();
request.addMarker("post-response");
mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, runnable));
}
@Override
public void postError(Request<?> request, VolleyError error) {
request.addMarker("post-error");
Response<?> response = Response.error(error);
mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, null));
}
// 還有一個內部類ResponseDeliveryRunnable下面講
...
}
通過構造函數,
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);
}
};
}
可以發現ExecutorDelivery成員變量Executor的執行操作是通過handler.post(command)將command操作傳遞到與Handler的相關聯的線程去執行。而ExecutorDelivery的三個post操作實際上是調用mResponsePoster.execute(command)。因此也許能夠猜到構造函數中的Handler極有可能是關聯着UI線程,查找一下ExecutorDelivery是在哪裏構造即可證實,通過RequestQueue的構造函數可以發現
public RequestQueue(Cache cache, Network network, int threadPoolSize) {
this(cache, network, threadPoolSize,new ExecutorDelivery(new Handler(Looper.getMainLooper())));
}
有了一點思路,那麼通過UI線程Handler做什麼呢,通過ExecutorDelivery的三個Post方法可以發現,傳遞的都是其內部類ResponseDeliveryRunnable的實例,看一下其源碼:
/**
* A Runnable used for delivering network responses to a listener on the
* main thread.
*/
@SuppressWarnings("rawtypes")
private class ResponseDeliveryRunnable implements Runnable {
private final Request mRequest;
private final Response mResponse;
private final Runnable mRunnable;
public ResponseDeliveryRunnable(Request request, Response response, Runnable runnable) {
mRequest = request;
mResponse = response;
mRunnable = runnable;
}
@SuppressWarnings("unchecked")
@Override
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();
}
}
}
可以發現ResponseDeliveryRunnable有三個成員變量,分別是Request,Response和Runnable,也許你會想這裏的Runnable有什麼用,在哪被使用了,下面再揭曉,重點看一下其run方法,發現它的邏輯是通過判斷request是否取消,結果是否成功,來看是否執行mRequest.deliverResponse(mResponse.result);和mRequest.deliverError(mResponse.error);,問題來了上面這兩個方法是幹什麼的??
查看Request的代碼,
/**
* Subclasses must implement this to perform delivery of the parsed
* response to their listeners. The given response is guaranteed to
* be non-null; responses that fail to parse are not delivered.
* @param response The parsed response returned by
* {@link #parseNetworkResponse(NetworkResponse)}
*/
abstract protected void deliverResponse(T response);
/**
* Delivers error message to the ErrorListener that the Request was
* initialized with.
*
* @param error Error details
*/
public void deliverError(VolleyError error) {
if (mErrorListener != null) {
mErrorListener.onErrorResponse(error);
}
}
發現deliverResponse是一個抽象方法,而deliverError是調用mErrorListener.onErrorResponse(error)傳遞VolleyError,而這裏的mErrorListener則是Response.ErrorListener接口。
到這裏有沒有一種恍然大悟的感覺,你應該猜到deliverResponse是通過調用Response.Listener接口傳遞結果的,那麼繼續查看Request子類中方法deliverResponse的實現
@Override
protected void deliverResponse(String response) {
if (mListener != null) {
mListener.onResponse(response);
}
}
可以發現子類中該方法寫法基本一樣,只是結果的參數不一樣而已。
現在小結一下,一個Request是怎麼在Response.Listener、Response.ErrorListener接口得到結果的
通過ExectorDelivery.post...操作,在UI線程中執行request.deliverResponse、request.deliverError方法,
而這兩個方法有通過調用Request其Response.Listener、Response.ErrorListener將結果傳遞出來。
那麼問題又來了,ExectorDelivery.post…操作在哪裏被執行,通過RequestQueue的成員mDelivery發現,在構造Dispatcher(NetworkDispatcher、CacheDispatcher)時mDelivery被傳遞過去,Dispatcher是一個工作線程,不斷獲取RequesetQueue隊列中的Requeset,並執行得到結果,再通過Delivery返回數據到UI線程。
問題又來了又來了,工作線程怎麼得到Request的結果Response。詳情請看下面問題二。
解答問題二:如何得到Request的結果Response
這裏涉及到的相關類有Network、跟NetWorkResponse,Cache
看到這裏應該明白Network通過HttpStack將Request轉換成HttpResponse,再將HttpResponse中的數據包裝成NetworkResponse
而這裏的HttpStack的兩個子類其實就是我們使用的HttpClient和HttpURLConnection。(下篇VolleyHTTP篇時講解)
那麼NetwoResponse是什麼?
先來了解一下Cache
可以看到Entry是存儲緩存數據的實體類,而NetworkResponse是存儲網絡數據結果的實體類
回到原來的問題,如何得到Request的結果Response,
現在有了NetworkResponse,怎麼實現呢?
看一下Requset源碼,可以發現
/**
* Subclasses must implement this to parse the raw network response
* and return an appropriate response type. This method will be
* called from a worker thread. The response will not be delivered
* if you return null.
* @param response Response from the network
* @return The parsed response, or null in the case of an error
*/
abstract protected Response<T> parseNetworkResponse(NetworkResponse response);
將NetworkResponse解析成Response是個抽象方法,也就是說在結果數據已經有了的前提下(NetworkResponse 對象的data數據,byte[]形式),對於具體怎麼樣的請求,那就有其自己去解析。比如StringRequest的parseNetworkResponse方法
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
這樣子我們也就可以自定義Request。
問題三:Volley緩存機制:CacheDispatcher及DiskBaseCache
CacheDispatcher是一個線程類,而上面講解的都是NetworkDispatcher這個線程類執行的操作:將Request的結果Response。
這裏提一下Volley在分配時默認分配有一個CacheDispatcher緩存操作線程和四個NetworkDispatcher網絡操作線程。
而NetworkDispatcher線程的工作是不斷的讀取RequsetQueue請求隊列中的Request並獲去結果。
那麼CacheDispatcher是幹嘛的呢??
根據前面兩個問題的解決思路,先看一下RequestQueue中的CacheDispatcher,發現其構造函數與NetworkDispatcher的差別在於CacheDispatcher多了一個mCacheQueue,其他對象完全一樣。
那麼這個mCacheQueue是什麼?應該是存儲正在緩存的Request的緩存隊列。
主要看一下run方法,看其是怎麼的緩存機制
@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();
Request<?> request;
while (true) {
// release previous request object to avoid leaking request object when mQueue is drained.
request = null;
try {
// Take a request from the queue.
request = mCacheQueue.take();
} catch (InterruptedException e) {
// We may have been interrupted because it was time to quit.
if (mQuit) {
return;
}
continue;
}
try {
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;
}
// If it is completely expired, just send it to the network.
if (entry.isExpired()) {
request.addMarker("cache-hit-expired");
request.setCacheEntry(entry);
mNetworkQueue.put(request);
continue;
}
// We have a cache hit; parse its data for delivery back to the request.
request.addMarker("cache-hit");
Response<?> response = request.parseNetworkResponse(
new NetworkResponse(entry.data, entry.responseHeaders));
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.
final Request<?> finalRequest = request;
mDelivery.postResponse(request, response, new Runnable() {
@Override
public void run() {
try {
mNetworkQueue.put(finalRequest);
} catch (InterruptedException e) {
// Not much we can do about this.
}
}
});
}
} catch (Exception e) {
VolleyLog.e(e, "Unhandled exception %s", e.toString());
}
}
}
根據其run方法可以看到,其緩存原理:
- 不斷在緩存隊列mCacheQueue中獲取Request。
- 如果無緩存(爲null或者過時),則添加到mNetworkQueue中等待從服務器中獲取數據
- 如果有緩存,判斷是否需要刷新數據
- 不需要則直接通過沒Delivery.post..方法傳結果遞到UI線程
- 需要刷新的話,則先通過Delivery.post…方法傳遞結果到UI線程,並且將請求添加到沒NetworkQueue中,即通過Delivery.post..( .. , .. , Runnable runnable)方法,這時候這個方法在這裏調用,突然覺得這個方法的神奇
在這裏也許你會發現通過 mCache.get(request.getCacheKey())獲取緩存,其實mCache的真實對象是Cache的子類DiskBaseCache,其功能類似於LruCache,內部是通過LinkedHashMap來保存緩存文件數據,讀取時對緩存文件進行讀取操作,這裏就不多講。
前天晚上寫項目寫到3點,昨晚回來寫這篇文章寫到了快3點,而且越寫越精神,哈哈,最重要的是堅持。
現在還寫了關於Volley的圖片處理源碼分析,有興趣的博友可以看看Volley – 圖片處理方式源碼分析
最後,如哪裏不足或者分析錯誤,非常歡迎指正,謝謝。