最近android端需要用到图片加载,volley用顺手了就顺带用了它的ImageRequest
因为需要考虑到加载速度及更新及时,势必会涉及图片在android端的缓存及更新。
虽然,用ImageRequest很快实现了功能,但出于保险起见,还是翻了下源码。
工作过程:添加请求==》加入缓存队列==》检查缓存==》视需要加入网络请求队列==》处理反馈
1,请求添加后,由于图片请求肯定是会开启缓存的,因此自然是会被加入到缓存对列;
2,查找缓存,并检查缓存是否过期,过期控制不细表(因该是基于ttl吧);
3,过期后加入网络请求队列,请求服务器;
4,请求后,如果是200就保存图片,如果是304则调用缓存;
过程很简单,至于细节。
1,过期控制。
由于我想要的是每次加载都去请求服务器,默认就是这样的实现,我也懒得去深究了。
2,该过程对应的关键源码。
1,
requestQueue.add(req)
2,
if(!request.shouldCache()) {//检测是否需要缓存
this.mNetworkQueue.add(request);
return request;
} else {
Map var8 = this.mWaitingRequests;
synchronized(this.mWaitingRequests) {
String cacheKey = request.getCacheKey();
if(this.mWaitingRequests.containsKey(cacheKey)) {
Object stagedRequests = (Queue)this.mWaitingRequests.get(cacheKey);
if(stagedRequests == null) {
stagedRequests = new LinkedList();
}
((Queue)stagedRequests).add(request);
this.mWaitingRequests.put(cacheKey, stagedRequests);
if(VolleyLog.DEBUG) {
VolleyLog.v("Request for cacheKey=%s is in flight, putting on hold.", new Object[]{cacheKey});
}
} else {
this.mWaitingRequests.put(cacheKey, (Object)null);
this.mCacheQueue.add(request);//加入缓存队列
}
return request;
}
}
3,
Entry entry = this.mCache.get(e.getCacheKey());
if(entry == null) {
e.addMarker("cache-miss");
this.mNetworkQueue.put(e);
} else if(!entry.isExpired()) {
e.addMarker("cache-hit");
Response response = e.parseNetworkResponse(new NetworkResponse(entry.data, entry.responseHeaders));
e.addMarker("cache-hit-parsed");
if(!entry.refreshNeeded()) {
this.mDelivery.postResponse(e, response);
} else {
e.addMarker("cache-hit-refresh-needed");
e.setCacheEntry(entry);
response.intermediate = true;
this.mDelivery.postResponse(e, response, new Runnable() {
public void run() {
try {
CacheDispatcher.this.mNetworkQueue.put(e);
} catch (InterruptedException var2) {
;
}
}
});
}
} else {
e.addMarker("cache-hit-expired");
e.setCacheEntry(entry);//给请求添加缓存,不然你304了上哪找就缓存去。
this.mNetworkQueue.put(e);//加入网络请求队列
}
4,
//如果304则尝试获取旧的缓存
Entry requestLifetime = request.getCacheEntry();
if(requestLifetime == null) {
return new NetworkResponse(304, (byte[])null, responseHeaders, true, SystemClock.elapsedRealtime() - requestStart);
}
requestLifetime.responseHeaders.putAll(responseHeaders);
return new NetworkResponse(304, requestLifetime.data, requestLifetime.responseHeaders, true, SystemClock.elapsedRealtime() - requestStart);
结束。至于volley本身网上源码分析太多了。
Queue&Dispatcher&Cache&Network反正就是这几样东西。
了解大概,用得到多少就去看多少,敬佩造轮子的,但是最终一切都是为了业务服务。