Volley是Google推出的一款比較輕巧的網絡請求框架,而且能夠對請求進行緩存,同時能夠實時取消請求,設置請求優先級,內置了ImageRequest,JsonRequest,JsonObjectRequest,JsonArrayRequest,StringRequest等,而且還支持自定義Request,基本上能知足平常的開發,當讓Volley原生並不支持文件上傳,可是能夠經過自定義Request來實現,Volley不只僅支持網絡請求,還支持圖片加載,這個主要是經過內置的ImageRequest來實現,Volley的工做原理大體以下:java
大體流程就是,當添加一個Request的時候,首先會被添加到CachaQueue中,算法
Volley的緩存跟常規的緩存不太一致,它並非直接去取緩存,而是構造了一個緩存隊列,存放Request,而後根據特有的key值去取緩存,若是緩存存在而且沒有過時,請求也沒有取消,那麼就直接解析緩存數據,發送到主線程,否則就直接加入到網絡請求隊列,從新請求網絡數據,Volley的源碼比較多,下面主要是從Request,RequestQueue,Dispatcher,Cache,這幾個類分析一下Volley的一些實現細節,畢竟大部分框架,原理都是一兩句話都能說清楚,可是有不少細節讓本身實現其實仍是挺困難的。數組
Request是一個單獨的類,實現了Comparable接口,主要是用來對請求進行排序,若是設置了請求的優先級,就會根據優先級來進行排序,若是沒有優先級就會按照請求加入的順序來排序。緩存
private final int mMethod;//請求類型,GET,POST
private final String mUrl;//請求的服務器地址
private final Object mLock = new Object();//用來給對象上鎖
private Response.ErrorListener mErrorListener;//請求失敗的監聽
private Integer mSequence;//請求的序列號,按照請求的順序依次遞增
private RequestQueue mRequestQueue;//請求隊列
private boolean mShouldCache = true;//是否須要緩存,默認開啓緩存
private boolean mCanceled = false;//請求是否取消,默認爲false
private boolean mResponseDelivered = false;//解析完的請求是否已經發送
private boolean mShouldRetryServerErrors = false;//遇到服務器異常是否須要重試
private RetryPolicy mRetryPolicy;//重試策略
private Cache.Entry mCacheEntry = null;//緩存的 對象,裏面封裝了不少跟緩存相關的信息
private Object mTag;//請求的tag
private NetworkRequestCompleteListener mRequestCompleteListener;//網絡請求完成回調的結果
//Request的生命週期記錄工具
private final MarkerLog mEventLog = MarkerLog.ENABLED ? new MarkerLog() : null;
複製代碼
Methodbash
public interface Method {
int DEPRECATED_GET_OR_POST = -1;
int GET = 0;
int POST = 1;
int PUT = 2;
int DELETE = 3;
int HEAD = 4;
int OPTIONS = 5;
int TRACE = 6;
int PATCH = 7;
}
複製代碼
因爲方法的辨識度比較高,因此Volley沒有采用枚舉,而是採用了接口內定義變量,節省開銷服務器
Priority網絡
public enum Priority {
LOW,
NORMAL,
HIGH,
IMMEDIATE
}
複製代碼
優先級更注重可讀性,因此Volley採用了枚舉app
@Deprecated
public Request(String url, Response.ErrorListener listener) {
this(Method.DEPRECATED_GET_OR_POST, url, listener);
}
public Request(int method, String url, Response.ErrorListener listener) {
mMethod = method;
mUrl = url;
mErrorListener = listener;
setRetryPolicy(new DefaultRetryPolicy());
mDefaultTrafficStatsTag = findDefaultTrafficStatsTag(url);
}
複製代碼
傳入method,url以及失敗的ErrorListener框架
cancelide
取消請求
public void cancel() {
synchronized (mLock) {
mCanceled = true;//改變請求標誌位
mErrorListener = null;//回調接口置空
}
}
複製代碼
compareTo
設置請求優先級
@Override
public int compareTo(Request<T> other) {
//獲取請求優先級
Priority left = this.getPriority();
Priority right = other.getPriority();
//請求優先級默認爲Normal
//1.先比較請求優先級,若是相等再比較請求加入的順序
return left == right ?
this.mSequence - other.mSequence :
right.ordinal() - left.ordinal();
}
複製代碼
finish
通知RequestQueue,這個請求已經結束
void finish(final String tag) {
if (mRequestQueue != null) {
//通知隊列移除當前請求
mRequestQueue.finish(this);
}
if (MarkerLog.ENABLED) {
final long threadId = Thread.currentThread().getId();
//判斷當前線程是否爲主線程,不是的話切換到主線程
if (Looper.myLooper() != Looper.getMainLooper()) {
//經過PostRunnable的方式,保證請求結束的打印時間是有序的
Handler mainThread = new Handler(Looper.getMainLooper());
mainThread.post(new Runnable() {
@Override
public void run() {
mEventLog.add(tag, threadId);
mEventLog.finish(Request.this.toString());
}
});
return;
}
mEventLog.add(tag, threadId);
mEventLog.finish(this.toString());
}
}
複製代碼
getCacheKey
默認做爲請求的服務器地址做爲key,實際開發過程當中須要經過MD5會比較好一點
public String getCacheKey() {
return getUrl();
}
複製代碼
抽象方法
Rquest是一個抽象類,裏面還有不少抽象犯法須要子類去實現
//解析網絡請求
abstract protected Response<T> parseNetworkResponse(NetworkResponse response);
//傳遞網絡請求結果
abstract protected void deliverResponse(T response);
//請求失敗的回調,由於不一樣的Request須要的返回類型不同,須要子類實現,可是請求失敗確是共同的
//因此Volley作了一些封裝
public void deliverError(VolleyError error) {
Response.ErrorListener listener;
synchronized (mLock) {
listener = mErrorListener;
}
if (listener != null) {
listener.onErrorResponse(error);
}
}
複製代碼
RequesQueue其實是全部隊列的一個管理類,包含正在進行中的隊列集合mCurrentRequests,緩存隊列mCacheQueue,網絡隊列mNetworkQueue等
//Request添加進去後的序列號
private final AtomicInteger mSequenceGenerator = new AtomicInteger();
//正在進行中的請求集合,採用HashSet實現
private final Set<Request<?>> mCurrentRequests = new HashSet<Request<?>>();
//請求的緩存隊列,採用PriorityBlockingQueue實現,能夠根據優先級來出隊
private final PriorityBlockingQueue<Request<?>> mCacheQueue =
new PriorityBlockingQueue<>();
//請求的網絡隊列,採用PriorityBlockingQueue實現
private final PriorityBlockingQueue<Request<?>> mNetworkQueue =
new PriorityBlockingQueue<>();
//網絡請求分發器的數量,默認爲4個
private static final int DEFAULT_NETWORK_THREAD_POOL_SIZE = 4;
//數據的緩存
private final Cache mCache;
//網絡請求的實際執行者
private final Network mNetwork;
//網絡請求返回結果的分發者
private final ResponseDelivery mDelivery;
//網絡請求分發器數組
private final NetworkDispatcher[] mDispatchers;
//緩存分發器線程
private CacheDispatcher mCacheDispatcher;
//網絡請求完成的監聽器集合
private final List<RequestFinishedListener> mFinishedListeners =new ArrayList<>();
複製代碼
public RequestQueue(Cache cache, Network network, int threadPoolSize) {
this(cache, network, threadPoolSize,
new ExecutorDelivery(new Handler(Looper.getMainLooper())));
}
public RequestQueue(Cache cache, Network network) {
this(cache, network, DEFAULT_NETWORK_THREAD_POOL_SIZE);
}
//其它的構造方法最終仍是間接調用了這個方法
public RequestQueue(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery) {
mCache = cache;
mNetwork = network;
mDispatchers = new NetworkDispatcher[threadPoolSize];
mDelivery = delivery;
}
複製代碼
經過成員變量的註釋,比較清晰,就是默認初始化了一些變量
start
public void start() {
stop(); //終止正在進行的分發器,包括緩存的分發器以及網絡分發器
// 建立緩存分發器
mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);
//啓動緩存分發器
mCacheDispatcher.start();
// 根據定義的Dispatcher數組,建立網絡分發器
for (int i = 0; i < mDispatchers.length; i++) {
NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,mCache, mDelivery);
mDispatchers[i] = networkDispatcher;
//啓動網絡分發器
networkDispatcher.start();
}
}
public void stop() {
if (mCacheDispatcher != null) {
mCacheDispatcher.quit();
}
for (final NetworkDispatcher mDispatcher : mDispatchers) {
if (mDispatcher != null) {
mDispatcher.quit();
}
}
}
複製代碼
add
public <T> Request<T> add(Request<T> request) {
//將RequestQueue賦值給Request
request.setRequestQueue(this);
//同步添加到正在進行中的請求集合中去
synchronized (mCurrentRequests) {
mCurrentRequests.add(request);
}
//給請求設置序列號
request.setSequence(getSequenceNumber());
//添加Marker標記位
request.addMarker("add-to-queue");
if (!request.shouldCache()) {
//若是請求隊列不須要緩存,那麼直接加入到網絡對壘中
mNetworkQueue.add(request);
return request;
}
//添加進緩存隊列
mCacheQueue.add(request);
return request;
}
複製代碼
cancel
public void cancelAll(final Object tag) {
if (tag == null) {
throw new IllegalArgumentException("Cannot cancelAll with a null tag");
}
cancelAll(new RequestFilter() {
@Override
public boolean apply(Request<?> request) {
//經過tag來匹配須要取消的請求
return request.getTag() == tag;
}
});
}
//經過RequestFilter來過濾須要取消的請求
public void cancelAll(RequestFilter filter) {
synchronized (mCurrentRequests) {
for (Request<?> request : mCurrentRequests) {
if (filter.apply(request)) {
request.cancel();
}
}
}
}
複製代碼
finish
<T> void finish(Request<T> request) {
// 從正在進行的請求中移除
synchronized (mCurrentRequests) {
mCurrentRequests.remove(request);
}
synchronized (mFinishedListeners) {
//移除回調接口
for (RequestFinishedListener<T> listener : mFinishedListeners) {
listener.onRequestFinished(request);
}
}
}
複製代碼
Volley提供了兩個分發器,一個是CacheDispatcher,一個是NetworkDispatcher,實際上就是兩個線程,而後進行了死循環,不斷地從緩存隊列跟網絡隊列中進行取Request來進行分發。
//Debug模式的標誌
private static final boolean DEBUG = VolleyLog.DEBUG;
//緩存隊列,採用BlockingQueue實現生產者消費者模式
private final BlockingQueue<Request<?>> mCacheQueue;
//網絡隊列,採用BlockingQueue實現生產者消費者模式
private final BlockingQueue<Request<?>> mNetworkQueue;
//緩存類
private final Cache mCache;
//網絡請求結果分發類
private final ResponseDelivery mDelivery;
//CacheDispatcher是否退出的標誌
private volatile boolean mQuit = false;
//等待管理隊列管理器
private final WaitingRequestManager mWaitingRequestManager;
複製代碼
public CacheDispatcher( BlockingQueue<Request<?>> cacheQueue, BlockingQueue<Request<?>> networkQueue, Cache cache, ResponseDelivery delivery) {
mCacheQueue = cacheQueue;
mNetworkQueue = networkQueue;
mCache = cache;
mDelivery = delivery;
mWaitingRequestManager = new WaitingRequestManager(this);
}
複製代碼
CacheDispatcher持有cacheQueue,networkQueue,cache,delivery這幾個類
@Override
public void run() {
if (DEBUG) VolleyLog.v("start new dispatcher");
//設置線程優先級
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//緩存初始化,待會在緩存中具體分析
mCache.initialize();
while (true) {
try {
//死循環
processRequest();
} catch (InterruptedException e) {
// We may have been interrupted because it was time to quit.
if (mQuit) {
return;
}
}
}
}
複製代碼
processRequest
private void processRequest() throws InterruptedException {
//從緩存隊列中取隊列
final Request<?> request = mCacheQueue.take();
//給取出的Requet打上標記
request.addMarker("cache-queue-take");
//若是請求已取消,結束掉這個請求
if (request.isCanceled()) {
request.finish("cache-discard-canceled");
return;
}
//拿到緩存的entry
Cache.Entry entry = mCache.get(request.getCacheKey());
//緩存數據爲空,就將Request添加進mNetworkQueue
if (entry == null) {
request.addMarker("cache-miss");
if (!mWaitingRequestManager.maybeAddToWaitingRequests(request)) {
mNetworkQueue.put(request);
}
return;
}
// 緩存過時,直接加入到網絡隊列
if (entry.isExpired()) {
request.addMarker("cache-hit-expired");
request.setCacheEntry(entry);
if (!mWaitingRequestManager.maybeAddToWaitingRequests(request)) {
mNetworkQueue.put(request);
}
return;
}
//緩存有效,直接解析發送給主線程
request.addMarker("cache-hit");
Response<?> response = request.parseNetworkResponse(
new NetworkResponse(entry.data, entry.responseHeaders));
request.addMarker("cache-hit-parsed");
}
複製代碼
退出線程
public void quit() {
mQuit = true;
//中斷線程
interrupt();
}
複製代碼
//網絡請求隊列
private final BlockingQueue<Request<?>> mQueue;
//網絡請求的實際操做類
private final Network mNetwork;
//緩存類
private final Cache mCache;
//請求響應的結果發送者
private final ResponseDelivery mDelivery;
//線程是否發送的標誌
private volatile boolean mQuit = false;
複製代碼
public NetworkDispatcher(BlockingQueue<Request<?>> queue,
Network network, Cache cache, ResponseDelivery delivery) {
mQueue = queue;
mNetwork = network;
mCache = cache;
mDelivery = delivery;
}
複製代碼
對比CacheDispatcher,發現少了緩存隊列,不過也很好理解,由於既然都到了網絡這邊了,說明緩存確定GG了,因此只須要在獲取到網絡請求結果以後,放入緩存中就好了。
run方法其實跟CacheDispatcher是同樣的,只是processRequest有些區別
private void processRequest() throws InterruptedException {
long startTimeMs = SystemClock.elapsedRealtime();
//從隊列中取出一個隊列
Request<?> request = mQueue.take();
try {
request.addMarker("network-queue-take");
//請求取消,直接finished
if (request.isCanceled()) {
request.finish("network-discard-cancelled");
request.notifyListenerResponseNotUsable();
return;
}
addTrafficStatsTag(request);
// 進行網絡請求
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");
request.notifyListenerResponseNotUsable();
return;
}
// 解析網絡請求數據
Response<?> response = request.parseNetworkResponse(networkResponse);
request.addMarker("network-parse-complete");
//若是請求結果須要緩存,那麼緩存請求的結果
if (request.shouldCache() && response.cacheEntry != null) {
mCache.put(request.getCacheKey(), response.cacheEntry);
request.addMarker("network-cache-written");
}
// 將解析好的數據發送給主線程
request.markDelivered();
mDelivery.postResponse(request, response);
request.notifyListenerResponseReceived(response);
} catch (VolleyError volleyError) {
volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
parseAndDeliverNetworkError(request, volleyError);
request.notifyListenerResponseNotUsable();
} catch (Exception e) {
VolleyLog.e(e, "Unhandled exception %s", e.toString());
VolleyError volleyError = new VolleyError(e);
volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
mDelivery.postError(request, volleyError);
request.notifyListenerResponseNotUsable();
}
}
複製代碼
public void quit() {
mQuit = true;
//中斷線程
interrupt();
}
複製代碼
Volley的緩存主要是磁盤緩存,首先Volley提供了一個Cache接口,而後DiskBasedCache實現了這個接口,下面說一下這兩個類
public interface Cache {
Entry get(String key);
void put(String key, Entry entry);
void initialize();
void invalidate(String key, boolean fullExpire);
void remove(String key);
void clear();
class Entry {
public byte[] data;
public String etag;
public long serverDate;
public long lastModified;
public long ttl;
public long softTtl;
public Map<String, String> responseHeaders = Collections.emptyMap();
public List<Header> allResponseHeaders;
public boolean isExpired() {
return this.ttl < System.currentTimeMillis();
}
public boolean refreshNeeded() {
return this.softTtl < System.currentTimeMillis();
}
}
複製代碼
很常規的接口,只不過緩存的value不是請求的結果,而是封裝了請求的數據的一個Entry,能夠對緩存作一些判斷。
//當前緩存的容量
private long mTotalSize = 0;
//緩存的路徑
private final File mRootDirectory;
//分配的最大緩存容量
private final int mMaxCacheSizeInBytes;
//默認的最大緩存容量
private static final int DEFAULT_DISK_USAGE_BYTES = 5 * 1024 * 1024;
//緩存的負載因子,到達這個點以後會自動進行緩存清理
private static final float HYSTERESIS_FACTOR = 0.9f;
//底層採用LinkedHashMap實現Lru算法,按照使用的順序進行排序
private final Map<String, CacheHeader> mEntries =
new LinkedHashMap<String, CacheHeader>(16, .75f, true);
複製代碼
public DiskBasedCache(File rootDirectory, int maxCacheSizeInBytes) {
mRootDirectory = rootDirectory;
mMaxCacheSizeInBytes = maxCacheSizeInBytes;
}
public DiskBasedCache(File rootDirectory) {
this(rootDirectory, DEFAULT_DISK_USAGE_BYTES);
}
複製代碼
經過緩存的大小跟路徑初始化DiskBasedCache
*/
@Override
public synchronized void put(String key, Entry entry) {
//檢查容量是否合理,不合理就進行刪除
pruneIfNeeded(entry.data.length);
//獲取緩存的文件
File file = getFileForKey(key);
try {
BufferedOutputStream fos = new BufferedOutputStream(createOutputStream(file));
CacheHeader e = new CacheHeader(key, entry);
boolean success = e.writeHeader(fos);
if (!success) {
fos.close();
VolleyLog.d("Failed to write header for %s", file.getAbsolutePath());
throw new IOException();
}
fos.write(entry.data);
fos.close();
//緩存數據
putEntry(key, e);
return;
} catch (IOException e) {
}
boolean deleted = file.delete();
if (!deleted) {
VolleyLog.d("Could not clean up file %s", file.getAbsolutePath());
}
}
複製代碼
pruneIfNeed
private void pruneIfNeeded(int neededSpace) {
//若是現有容量+即將存儲的容量小於最大容量,返回
if ((mTotalSize + neededSpace) < mMaxCacheSizeInBytes) {
return;
}
long before = mTotalSize;
int prunedFiles = 0;
long startTime = SystemClock.elapsedRealtime();
Iterator<Map.Entry<String, CacheHeader>> iterator = mEntries.entrySet().iterator();
//遍歷LinkedHashMap,刪除鏈表頭部的數據
while (iterator.hasNext()) {
Map.Entry<String, CacheHeader> entry = iterator.next();
CacheHeader e = entry.getValue();
boolean deleted = getFileForKey(e.key).delete();
if (deleted) {
mTotalSize -= e.size;
} else {
VolleyLog.d("Could not delete cache entry for key=%s, filename=%s",
e.key, getFilenameForKey(e.key));
}
iterator.remove();
prunedFiles++;
if ((mTotalSize + neededSpace) < mMaxCacheSizeInBytes * HYSTERESIS_FACTOR) {
break;
}
}
}
複製代碼
@Override
public synchronized Entry get(String key) {
//經過key獲取緩存的entry
CacheHeader entry = mEntries.get(key);
//若是entry爲null的話直接返回
if (entry == null) {
return null;
}
//經過key獲取到file文件
File file = getFileForKey(key);
try {
CountingInputStream cis = new CountingInputStream(
new BufferedInputStream(createInputStream(file)), file.length());
try {
CacheHeader entryOnDisk = CacheHeader.readHeader(cis);
if (!TextUtils.equals(key, entryOnDisk.key)) {
// File was shared by two keys and now holds data for a different entry!
VolleyLog.d("%s: key=%s, found=%s",
file.getAbsolutePath(), key, entryOnDisk.key);
// Remove key whose contents on disk have been replaced.
removeEntry(key);
return null;
}
byte[] data = streamToBytes(cis, cis.bytesRemaining());
//將解析好的數據返回
return entry.toCacheEntry(data);
} finally {
// Any IOException thrown here is handled by the below catch block by design.
//noinspection ThrowFromFinallyBlock
cis.close();
}
} catch (IOException e) {
VolleyLog.d("%s: %s", file.getAbsolutePath(), e.toString());
remove(key);
return null;
}
}
複製代碼
private int mCurrentTimeoutMs;//超時時間
private int mCurrentRetryCount;//已重試次數
private final int mMaxNumRetries;//最大重試次數
private final float mBackoffMultiplier;//失敗後重連的間隔因子
public static final int DEFAULT_TIMEOUT_MS = 2500;//默認超時時間
public static final int DEFAULT_MAX_RETRIES = 1;//默認重試次數
public static final float DEFAULT_BACKOFF_MULT = 1f;//默認的失敗以後重連的間隔因子爲1
複製代碼
public DefaultRetryPolicy() {
this(DEFAULT_TIMEOUT_MS, DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT);
}
public DefaultRetryPolicy(int initialTimeoutMs, int maxNumRetries, float backoffMultiplier) {
mCurrentTimeoutMs = initialTimeoutMs;
mMaxNumRetries = maxNumRetries;
mBackoffMultiplier = backoffMultiplier;
}
複製代碼
傳入超時時間,最大重試次數,重試間隔
@Override
public void retry(VolleyError error) throws VolleyError {
mCurrentRetryCount++;
//計算重試時間
mCurrentTimeoutMs += (mCurrentTimeoutMs * mBackoffMultiplier);
if (!hasAttemptRemaining()) {
//若是到達最大次數,仍是失敗就拋異常
throw error;
}
}
複製代碼
Volley不只支持網絡請求,還能夠用來加載圖片,主要相關的兩個核心類是ImageLoader跟ImageRequest
private final RequestQueue mRequestQueue;//請求隊列
private int mBatchResponseDelayMs = 100;//請求響應結果發送延時
private final ImageCache mCache;//圖片緩存
//用HashMap來保存延時的請求
private final HashMap<String, BatchedImageRequest> mInFlightRequests =
new HashMap<String, BatchedImageRequest>();
//HashMap來保存延時的請求響應結果
private final HashMap<String, BatchedImageRequest> mBatchedResponses =
new HashMap<String, BatchedImageRequest>();
//切換線程的Handler
private final Handler mHandler = new Handler(Looper.getMainLooper());
複製代碼
public ImageLoader(RequestQueue queue, ImageCache imageCache) {
mRequestQueue = queue;
mCache = imageCache;
}
複製代碼
public ImageContainer get(String requestUrl, final ImageListener listener) {
return get(requestUrl, listener, 0, 0);
}
複製代碼
間接調用
public ImageContainer get(String requestUrl, ImageListener imageListener, int maxWidth, int maxHeight) {
return get(requestUrl, imageListener, maxWidth, maxHeight, ScaleType.CENTER_INSIDE);
}
複製代碼
繼續調用
public ImageContainer get(String requestUrl, ImageListener imageListener, int maxWidth, int maxHeight, ScaleType scaleType) {
// 檢測是否在主線程
throwIfNotOnMainThread();
//經過轉換獲得緩存的key
final String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight, scaleType);
// 從緩存中查找對應的bitmap
Bitmap cachedBitmap = mCache.getBitmap(cacheKey);
if (cachedBitmap != null) {
//找到直接返回
ImageContainer container = new ImageContainer(cachedBitmap, requestUrl, null, null);
imageListener.onResponse(container, true);
return container;
}
// 緩存失敗,初始化ImageContainer
ImageContainer imageContainer =
new ImageContainer(null, requestUrl, cacheKey, imageListener);
//回調
imageListener.onResponse(imageContainer, true);
// 判斷當前的請求是否在mBatchedResponses中
BatchedImageRequest request = mInFlightRequests.get(cacheKey);
if (request != null) {
// If it is, add this request to the list of listeners.
request.addContainer(imageContainer);
return imageContainer;
}
// 傳達
Request<Bitmap> newRequest = makeImageRequest(requestUrl, maxWidth, maxHeight, scaleType,cacheKey);
mRequestQueue.add(newRequest);
mInFlightRequests.put(cacheKey, new BatchedImageRequest(newRequest, imageContainer));
return imageContainer;
}
複製代碼
get方法返回的是一個ImageContainer,裏面包好了不少跟Image相關的信息,相似Cache,mCacheKey,mRequestUrl,mListener。
ImageRequest繼承自Request,而後定義的泛型是Bitmap
//超時時間
public static final int DEFAULT_IMAGE_TIMEOUT_MS = 1000;
//默認的重試次數
public static final int DEFAULT_IMAGE_MAX_RETRIES = 2;
//默認重試延遲因子
public static final float DEFAULT_IMAGE_BACKOFF_MULT = 2f;
private final Object mLock = new Object();//全局對象鎖
private Response.Listener<Bitmap> mListener;//回調監聽
private final Config mDecodeConfig;//解碼的配置信息
private final int mMaxWidth;//ImageView傳入的最大寬度
private final int mMaxHeight;//ImageView傳入的最大高度
private final ScaleType mScaleType;//縮放類型
private static final Object sDecodeLock = new Object();//解碼的同步鎖
複製代碼
@Deprecated
public ImageRequest(String url, Response.Listener<Bitmap> listener, int maxWidth, int maxHeight, Config decodeConfig, Response.ErrorListener errorListener) {
this(url, listener, maxWidth, maxHeight,
ScaleType.CENTER_INSIDE, decodeConfig, errorListener);
}
public ImageRequest(String url, Response.Listener<Bitmap> listener, int maxWidth, int maxHeight, ScaleType scaleType, Config decodeConfig, Response.ErrorListener errorListener) {
super(Method.GET, url, errorListener);
setRetryPolicy(new DefaultRetryPolicy(DEFAULT_IMAGE_TIMEOUT_MS, DEFAULT_IMAGE_MAX_RETRIES,
DEFAULT_IMAGE_BACKOFF_MULT));
mListener = listener;
mDecodeConfig = decodeConfig;
mMaxWidth = maxWidth;
mMaxHeight = maxHeight;
mScaleType = scaleType;
}
複製代碼
構造方法裏面都是一些配置信息,沒什麼好說的
@Override
public void cancel() {
super.cancel();
synchronized (mLock) {
mListener = null;
}
}
複製代碼
跟前面的一個套路,不解釋
網絡請求回來以後,通過傳遞最終到了doParse方法
private Response<Bitmap> doParse(NetworkResponse response) {
//拿到字節數組
byte[] data = response.data;
BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
Bitmap bitmap = null;
if (mMaxWidth == 0 && mMaxHeight == 0) {
//傳入的寬高都爲0,不縮放,直接返回原始尺寸
decodeOptions.inPreferredConfig = mDecodeConfig;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
} else {
// If we have to resize this image, first get the natural bounds.
//先不加載進內存
decodeOptions.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
//獲取實際寬高
int actualWidth = decodeOptions.outWidth;
int actualHeight = decodeOptions.outHeight;
// 進行比例縮放,獲取時間寬高
int desiredWidth = getResizedDimension(mMaxWidth, mMaxHeight,
actualWidth, actualHeight, mScaleType);
int desiredHeight = getResizedDimension(mMaxHeight, mMaxWidth,
actualHeight, actualWidth, mScaleType);
// 進行縮放
decodeOptions.inJustDecodeBounds = false;
decodeOptions.inSampleSize =
findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight);
Bitmap tempBitmap =
BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
// 若是有必要的話,把獲得的bitmap的最大邊進行壓縮來適應尺寸
if (tempBitmap != null && (tempBitmap.getWidth() > desiredWidth ||
tempBitmap.getHeight() > desiredHeight)) {
bitmap = Bitmap.createScaledBitmap(tempBitmap,
desiredWidth, desiredHeight, true);
tempBitmap.recycle();
} else {
bitmap = tempBitmap;
}
}
if (bitmap == null) {
//解析失敗回調
return Response.error(new ParseError(response));
} else {
//解析成功回調
return Response.success(bitmap, HttpHeaderParser.parseCacheHeaders(response));
}
}
複製代碼
Volley加載圖片的大體流程就到了這裏,可能會有些奇怪,Volley並無採用Lrucache在內存中進行緩存,是由於ImageRequest繼承自Request,因此就依賴於緩存隊列,只有File的緩存,可能這也是爲何提到圖片加載你們可能會想到不少的Fresco,Glide,Picasso,可是不多人會想到Volley,提到Volley想到的仍是網絡請求,沒有LRUCache應該是最主要的緣由了。
Volley是一款擴展性很強的框架,抽取了Request基類,用戶能夠自定義任意的Request,底層並無使用線程池,而是採用了四個網絡線程從RequestQueue中取數據,若是是數據量較小的網絡請求,使用起來比較靈活,若是網絡請求比較耗時,那麼Volley的四個線程可能就不夠用了,咱們能夠建立更多的線程,可是線程的開銷會很高,並且對線程的利用率不大,這個時候就須要使用線程池了。Volley提供圖片加載的功能,可是沒有實現內存緩存,因此性能不是很高。Volley原生沒有提供圖片上傳功能,不過因爲他的擴展性很好,因此咱們能夠本身繼承Request類來實現這個功能。