概述
在Android開發(fā)界,大家都知到square出品必屬精品,圖片加載庫Picasso自然也是。本文就從源碼角度,詳細分析下Picasso。
基本使用
下面的代碼為一次簡單的網(wǎng)絡(luò)加載圖片
Picasso.with(getApplicationContext())
.load("http://www.qlnh.com/uploads/image/20160714/20160714114238_6824.jpg")
.placeholder(holderDrawable)
.error(errorDrawable)
.into(imageView);
可以看到,整個調(diào)用流程結(jié)構(gòu)非常清晰,鏈式方法看起來也讓人賞心悅目。當(dāng)然這只是一個基本的網(wǎng)絡(luò)加載圖片例子,你也可以配置很多其他參數(shù),如圖片裁減,旋轉(zhuǎn)等等。
下面詳細分析Picasso
的核心類及加載流程
Picasso的初始化
Picasso庫
采用了門面設(shè)計模式,調(diào)用都是從Picasso類
開始的,而Picasso
內(nèi)部組件的初始化也是在Picasso類
中執(zhí)行的。如果不需要自定義Picasso
,直接使用單例模式Picasso with(Context context)
獲取Picasso
實例就可以了,而如果需要自定義Picasso
類則可以在調(diào)用Picasso with(Context context)
之前先通過setSingletonInstance(Picasso picasso)
來設(shè)置Picasso
。
下面來看看Picasso
有那些可以自定義的組件
public static class Builder {
private final Context context;
private Downloader downloader; //下載器
private ExecutorService service; //網(wǎng)絡(luò)任務(wù)線程池
private Cache cache; //內(nèi)存緩存
private Listener listener; //onImageLoadFailed 監(jiān)聽
private RequestTransformer transformer; //Request提交前的預(yù)留hook接口
private List<RequestHandler> requestHandlers; //請求處理者集合
private Bitmap.Config defaultBitmapConfig; //默認bitmap設(shè)置信息
private boolean indicatorsEnabled; //是否debug 信息提示顯示
private boolean loggingEnabled; //是否打印log
...
如果沒有自定義,Picasso
類就會使用默認配置。
public Picasso build() {
Context context = this.context;
if (downloader == null) {
downloader = Utils.createDefaultDownloader(context);
}
if (cache == null) {
cache = new LruCache(context);
}
if (service == null) {
service = new PicassoExecutorService();
}
if (transformer == null) {
transformer = RequestTransformer.IDENTITY;
}
Stats stats = new Stats(cache);
Dispatcher dispatcher = new Dispatcher(context, service, HANDLER, downloader, cache, stats);
return new Picasso(context, dispatcher, cache, listener, transformer, requestHandlers, stats,
defaultBitmapConfig, indicatorsEnabled, loggingEnabled);
}
下面來看看這些組件的默認配置:
- downloader
downloader 類是對網(wǎng)絡(luò)實現(xiàn)的抽象接口,有Response load(Uri uri, int networkPolicy)
,void shutdown();
,InputStream getInputStream()
等方法。下面的創(chuàng)建默認實現(xiàn)的方法中會反射判斷項目是否依賴okhttp
庫,如果有okhttp
庫就使用okhttp
來實現(xiàn)downloader
,否則就采用httpurlconnection
來實現(xiàn)。其實在volley
,glide
等開源庫都有如此設(shè)計,可以方便切換okhttp
或者httpurlconnection
作為網(wǎng)絡(luò)請求的默認實現(xiàn)。
static Downloader createDefaultDownloader(Context context) {
try {
Class.forName("com.squareup.okhttp.OkHttpClient");
return OkHttpLoaderCreator.create(context);
} catch (ClassNotFoundException ignored) {
}
return new UrlConnectionDownloader(context);
}
- cache
cache
接口作為內(nèi)存緩存的抽象接口有以下方法
/** Retrieve an image for the specified {@code key} or {@code null}. */
Bitmap get(String key);
/** Store an image in the cache for the specified {@code key}. */
void set(String key, Bitmap bitmap);
/** Returns the current size of the cache in bytes. */
int size();
/** Returns the maximum size in bytes that the cache can hold. */
int maxSize();
/** Clears the cache. */
void clear();
/** Remove items whose key is prefixed with {@code keyPrefix}. */
void clearKeyUri(String keyPrefix);
默認的實現(xiàn)為LruCache
,既當(dāng)內(nèi)存達到最大值時移除最早的緩存
- service
默認實現(xiàn)為PicassoExecutorService
private static final int DEFAULT_THREAD_COUNT = 3;
PicassoExecutorService() {
super(DEFAULT_THREAD_COUNT, DEFAULT_THREAD_COUNT, 0, TimeUnit.MILLISECONDS,
new PriorityBlockingQueue<Runnable>(), new Utils.PicassoThreadFactory());
}
這個也好理解,就是一個線程數(shù)為3的固定線程池,注意這個線程池的的等待隊列為PriorityBlockingQueue
。另一方面,Picasso
中注冊了,接受了網(wǎng)絡(luò)信號變化的廣播接收者,當(dāng)網(wǎng)絡(luò)切換時會根據(jù)網(wǎng)絡(luò)類型動態(tài)變化線程池的線程數(shù)。
- Dispatcher
Dispatcher
為Picasso
非常重要的一個類,所有任務(wù)的執(zhí)行都要經(jīng)它之手。其沒有對使用者提供自定義選項。下面是一些dispatcher
的方法,基本都是將任務(wù)發(fā)送到其內(nèi)部的一個handler
處理,這個handler
是運行的handlerthread
的專門來處理任務(wù)派發(fā)的。
...
void dispatchSubmit(Action action) {
handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));
}
void dispatchCancel(Action action) {
handler.sendMessage(handler.obtainMessage(REQUEST_CANCEL, action));
}
void dispatchResumeTag(Object tag) {
handler.sendMessage(handler.obtainMessage(TAG_RESUME, tag));
}
void dispatchComplete(BitmapHunter hunter) {
handler.sendMessage(handler.obtainMessage(HUNTER_COMPLETE, hunter));
}
void dispatchRetry(BitmapHunter hunter) {
handler.sendMessageDelayed(handler.obtainMessage(HUNTER_RETRY, hunter), RETRY_DELAY);
}
void dispatchFailed(BitmapHunter hunter) {
handler.sendMessage(handler.obtainMessage(HUNTER_DECODE_FAILED, hunter));
}
void dispatchNetworkStateChange(NetworkInfo info) {
handler.sendMessage(handler.obtainMessage(NETWORK_STATE_CHANGE, info));
}
...
- transformer &stats
這兩個組件都是非核心組件,transformer 是給提交request前的一個hook接口,默認是直接返回request
RequestTransformer IDENTITY = new RequestTransformer() {
@Override public Request transformRequest(Request request) {
return request;
}
};
而stats 是負責(zé)統(tǒng)計的類,與核心功能無關(guān)。
核心類
下面以一次圖片加載過程的順序來介紹下這些核心類
Request&RequestCreator
Request
是封裝圖片請求(包括url,圖片變形參數(shù),請求優(yōu)先級)等的model類,而RequestCreator
則是創(chuàng)建Request
的輔助類,其是非常重要的一個類。
我們通過Picasso.load()
方法會返回一個RequestCreator
對象,之后我們可以在RequestCreator
上設(shè)置placeholder
、error
等狀態(tài)的圖片,也可以設(shè)置transform
,rotate
等參數(shù)。最終通過into()
方法,創(chuàng)建request
并提交. into()
方法有好幾種重載下面以target為imageview的into方法為例來分析一下.
public void into(ImageView target, Callback callback) {
long started = System.nanoTime();
checkMain(); //檢查是否主線程,若不是拋出異常
if (target == null) {
throw new IllegalArgumentException("Target must not be null.");
}
if (!data.hasImage()) { //檢查是否有設(shè)置url或者resId,若都沒有拋出異常
picasso.cancelRequest(target);
if (setPlaceholder) {
setPlaceholder(target, getPlaceholderDrawable());
}
return;
}
if (deferred) {//fit()模式
if (data.hasSize()) { //fit()模式是適應(yīng)target的寬高加載,不能手動設(shè)置resize,如果設(shè)置就拋出異常
throw new IllegalStateException("Fit cannot be used with resize.");
}
int width = target.getWidth();
int height = target.getHeight();
if (width == 0 || height == 0) {
if (setPlaceholder) {
setPlaceholder(target, getPlaceholderDrawable());
}
picasso.defer(target, new DeferredRequestCreator(this, target, callback));
return;
}
data.resize(width, height);
}
Request request = createRequest(started); //創(chuàng)建Request
String requestKey = createKey(request);
if (shouldReadFromMemoryCache(memoryPolicy)) { //是否從內(nèi)存讀取
Bitmap bitmap = picasso.quickMemoryCacheCheck(requestKey);
if (bitmap != null) {
picasso.cancelRequest(target);
setBitmap(target, picasso.context, bitmap, MEMORY, noFade, picasso.indicatorsEnabled);
if (picasso.loggingEnabled) {
log(OWNER_MAIN, VERB_COMPLETED, request.plainId(), "from " + MEMORY);
}
if (callback != null) {
callback.onSuccess();
}
return;
}
}
if (setPlaceholder) { //設(shè)置placeholder
setPlaceholder(target, getPlaceholderDrawable());
}
Action action = //創(chuàng)建Action
new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
errorDrawable, requestKey, tag, callback, noFade);
picasso.enqueueAndSubmit(action); //action入隊
}
Action
Action
是封裝了請求和target及內(nèi)存策略等參數(shù)的類,在上一節(jié)的Requestcreator.into()
方法中創(chuàng)建,然后交由Picasso
類執(zhí)行(picasso.enqueueAndSubmit(action)
),下面來看看這個提交過程都做了什么
//Picasso類中
void enqueueAndSubmit(Action action) {
Object target = action.getTarget();
if (target != null && targetToAction.get(target) != action) {//取消target此前的任務(wù)
// This will also check we are on the main thread.
cancelExistingRequest(target); //取消已存在的action
targetToAction.put(target, action); //添加到target-action map集合
}
submit(action);
}
void submit(Action action) {
dispatcher.dispatchSubmit(action); //委托dispatcher執(zhí)行
}
//Dispatcher類中
void performSubmit(Action action) {
performSubmit(action, true);
}
void performSubmit(Action action, boolean dismissFailed) {
if (pausedTags.contains(action.getTag())) {
pausedActions.put(action.getTarget(), action); //如果需要pause則pause
if (action.getPicasso().loggingEnabled) {
log(OWNER_DISPATCHER, VERB_PAUSED, action.request.logId(),
"because tag '" + action.getTag() + "' is paused");
}
return;
}
BitmapHunter hunter = hunterMap.get(action.getKey());
if (hunter != null) { //如果hunter已經(jīng)存在,attach
hunter.attach(action);
return;
}
if (service.isShutdown()) { //檢查線程池
if (action.getPicasso().loggingEnabled) {
log(OWNER_DISPATCHER, VERB_IGNORED, action.request.logId(), "because shut down");
}
return;
}
hunter = forRequest(action.getPicasso(), this, cache, stats, action); //創(chuàng)建hunter
hunter.future = service.submit(hunter); //向線程池提交hunter
hunterMap.put(action.getKey(), hunter);
if (dismissFailed) {
failedActions.remove(action.getTarget());
}
if (action.getPicasso().loggingEnabled) {
log(OWNER_DISPATCHER, VERB_ENQUEUED, action.request.logId());
}
}
上面代碼先是判斷了target是否已存在action,如果是則pause之前的target,然后Picasso
類把任務(wù)的啟動交給dispatcher
來執(zhí)行,dispatcher
檢查action對應(yīng)的hunter
是否已創(chuàng)建,如果創(chuàng)建則直接將action
attachhunter
即可,如果hunter
沒有創(chuàng)建則創(chuàng)建hunter
并將其提交給線程池執(zhí)行.
BitmapHunter
由上一節(jié)可知一個請求任務(wù)最終的執(zhí)行者就是bitmaphunter
,先來看看bitmaphunter
的創(chuàng)建:
static BitmapHunter forRequest(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats,
Action action) {
Request request = action.getRequest();
List<RequestHandler> requestHandlers = picasso.getRequestHandlers();
// Index-based loop to avoid allocating an iterator.
//noinspection ForLoopReplaceableByForEach
for (int i = 0, count = requestHandlers.size(); i < count; i++) {
RequestHandler requestHandler = requestHandlers.get(i);
if (requestHandler.canHandleRequest(request)) {
return new BitmapHunter(picasso, dispatcher, cache, stats, action, requestHandler);
}
}
return new BitmapHunter(picasso, dispatcher, cache, stats, action, ERRORING_HANDLER);
}
BitmapHunter(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats, Action action,
RequestHandler requestHandler) {
this.sequence = SEQUENCE_GENERATOR.incrementAndGet();
this.picasso = picasso;
this.dispatcher = dispatcher;
this.cache = cache;
this.stats = stats;
this.action = action;
this.key = action.getKey();
this.data = action.getRequest();
this.priority = action.getPriority();
this.memoryPolicy = action.getMemoryPolicy();
this.networkPolicy = action.getNetworkPolicy();
this.requestHandler = requestHandler;
this.retryCount = requestHandler.getRetryCount();
}
bitmaphunter
對象的創(chuàng)建是有static 方法forRequest
完成的,其主要工作是根據(jù)request尋找到可以處理此request
的RequestHandler
,這里的尋找過程采用了責(zé)任鏈模式,可以借鑒一下.
Picasso
對象的requestHandlers
是在Picasso
初始化時創(chuàng)建的,其有以下幾種
List<RequestHandler> allRequestHandlers =
new ArrayList<RequestHandler>(builtInHandlers + extraCount);
// ResourceRequestHandler needs to be the first in the list to avoid
// forcing other RequestHandlers to perform null checks on request.uri
// to cover the (request.resourceId != 0) case.
allRequestHandlers.add(new ResourceRequestHandler(context));
if (extraRequestHandlers != null) {
allRequestHandlers.addAll(extraRequestHandlers);
}
allRequestHandlers.add(new ContactsPhotoRequestHandler(context)); //聯(lián)系人頭像
allRequestHandlers.add(new MediaStoreRequestHandler(context)); //媒體存儲
allRequestHandlers.add(new ContentStreamRequestHandler(context)); //內(nèi)容提供者
allRequestHandlers.add(new AssetRequestHandler(context)); //assert讀取
allRequestHandlers.add(new FileRequestHandler(context)); //文件讀取
allRequestHandlers.add(new NetworkRequestHandler(dispatcher.downloader, stats)); //網(wǎng)絡(luò)獲取
requestHandlers = Collections.unmodifiableList(allRequestHandlers);
通過責(zé)任鏈模式
我們可以很方便的擴展處理request的handler
再來看看bitmaphunter
類的run方法:
@Override public void run() {
try {
updateThreadName(data);
if (picasso.loggingEnabled) {
log(OWNER_HUNTER, VERB_EXECUTING, getLogIdsForHunter(this));
}
result = hunt(); //關(guān)鍵步驟,獲取bitmap
if (result == null) {
dispatcher.dispatchFailed(this); //獲取失敗
} else {
dispatcher.dispatchComplete(this); //獲取成功
}
} catch (Downloader.ResponseException e) { //異常處理
if (!e.localCacheOnly || e.responseCode != 504) {
exception = e;
}
dispatcher.dispatchFailed(this);
} catch (NetworkRequestHandler.ContentLengthException e) {
exception = e;
dispatcher.dispatchRetry(this);
} catch (IOException e) {
exception = e;
dispatcher.dispatchRetry(this);
} catch (OutOfMemoryError e) {
StringWriter writer = new StringWriter();
stats.createSnapshot().dump(new PrintWriter(writer));
exception = new RuntimeException(writer.toString(), e);
dispatcher.dispatchFailed(this);
} catch (Exception e) {
exception = e;
dispatcher.dispatchFailed(this);
} finally {
Thread.currentThread().setName(Utils.THREAD_IDLE_NAME);
}
}
Bitmap hunt() throws IOException {
Bitmap bitmap = null;
if (shouldReadFromMemoryCache(memoryPolicy)) { //從內(nèi)存緩存處理
bitmap = cache.get(key);
if (bitmap != null) {
stats.dispatchCacheHit();
loadedFrom = MEMORY;
if (picasso.loggingEnabled) {
log(OWNER_HUNTER, VERB_DECODED, data.logId(), "from cache");
}
return bitmap;
}
}
data.networkPolicy = retryCount == 0 ? NetworkPolicy.OFFLINE.index : networkPolicy;
RequestHandler.Result result = requestHandler.load(data, networkPolicy); //交由requestHandler獲取圖片
if (result != null) {
loadedFrom = result.getLoadedFrom();
exifRotation = result.getExifOrientation();
bitmap = result.getBitmap();
// If there was no Bitmap then we need to decode it from the stream.
if (bitmap == null) {
InputStream is = result.getStream();
try {
bitmap = decodeStream(is, data);
} finally {
Utils.closeQuietly(is);
}
}
}
if (bitmap != null) {
if (picasso.loggingEnabled) {
log(OWNER_HUNTER, VERB_DECODED, data.logId());
}
stats.dispatchBitmapDecoded(bitmap);
if (data.needsTransformation() || exifRotation != 0) {
synchronized (DECODE_LOCK) {
if (data.needsMatrixTransform() || exifRotation != 0) {
bitmap = transformResult(data, bitmap, exifRotation); //對圖片進行變形等操作
if (picasso.loggingEnabled) {
log(OWNER_HUNTER, VERB_TRANSFORMED, data.logId());
}
}
if (data.hasCustomTransformations()) { //處理自定義的變形操作
bitmap = applyCustomTransformations(data.transformations, bitmap);
if (picasso.loggingEnabled) {
log(OWNER_HUNTER, VERB_TRANSFORMED, data.logId(), "from custom transformations");
}
}
}
if (bitmap != null) {
stats.dispatchBitmapTransformed(bitmap);
}
}
}
return bitmap;
}
圖片的獲取就完成后,再交由dispatcher
去處理 dispatcher.dispatchComplete(this);
顯示
在BitmapHunter
獲取圖片成功后,會交由dispatcher.dispatchComplete(this);
處理,最終會執(zhí)行到以下
void performComplete(BitmapHunter hunter) {
if (shouldWriteToMemoryCache(hunter.getMemoryPolicy())) {
cache.set(hunter.getKey(), hunter.getResult()); //如果需要內(nèi)存緩存則添加到cache中
}
hunterMap.remove(hunter.getKey());
batch(hunter); //批量處理
if (hunter.getPicasso().loggingEnabled) {
log(OWNER_DISPATCHER, VERB_BATCHED, getLogIdsForHunter(hunter), "for completion");
}
}
private void batch(BitmapHunter hunter) {
if (hunter.isCancelled()) { //檢查是否取消
return;
}
batch.add(hunter); //向批處理集合中添加
if (!handler.hasMessages(HUNTER_DELAY_NEXT_BATCH)) { //如果沒有指定message則發(fā)送指定消息
handler.sendEmptyMessageDelayed(HUNTER_DELAY_NEXT_BATCH, BATCH_DELAY);
}
}
void performBatchComplete() {
List<BitmapHunter> copy = new ArrayList<BitmapHunter>(batch);
batch.clear();
mainThreadHandler.sendMessage(mainThreadHandler.obtainMessage(HUNTER_BATCH_COMPLETE, copy));
logBatch(copy);
}
這里主要有一個batch處理讓人費解, dispatcher
會以200ms
為一個周期區(qū)處理complete任務(wù),至于為什么要有這個操作,個人猜測可能是基于性能考慮吧.
最終,dispatcher
會將200ms
內(nèi)完成的任務(wù)發(fā)送到主線程(這個主線程handler定義在Picasso
類中),
主線程收到這個消息后會調(diào)用complete
方法,來看看這個方法:
void complete(BitmapHunter hunter) {
Action single = hunter.getAction();
List<Action> joined = hunter.getActions();
boolean hasMultiple = joined != null && !joined.isEmpty();
boolean shouldDeliver = single != null || hasMultiple;
if (!shouldDeliver) {
return;
}
Uri uri = hunter.getData().uri;
Exception exception = hunter.getException();
Bitmap result = hunter.getResult();
LoadedFrom from = hunter.getLoadedFrom();
if (single != null) {
deliverAction(result, from, single);
}
if (hasMultiple) {
//noinspection ForLoopReplaceableByForEach
for (int i = 0, n = joined.size(); i < n; i++) {
Action join = joined.get(i);
deliverAction(result, from, join);
}
}
if (listener != null && exception != null) {
listener.onImageLoadFailed(this, uri, exception);
}
}
private void deliverAction(Bitmap result, LoadedFrom from, Action action) {
if (action.isCancelled()) {
return;
}
if (!action.willReplay()) {
targetToAction.remove(action.getTarget());
}
if (result != null) {
if (from == null) {
throw new AssertionError("LoadedFrom cannot be null.");
}
action.complete(result, from);
if (loggingEnabled) {
log(OWNER_MAIN, VERB_COMPLETED, action.request.logId(), "from " + from);
}
} else {
action.error();
if (loggingEnabled) {
log(OWNER_MAIN, VERB_ERRORED, action.request.logId());
}
}
}
最終,action.complete(result, from);
會被調(diào)用,在這個方法里面會對target設(shè)置bitmap(還有些加載動畫等設(shè)置,此處不再贅述),至此圖片加載完成。
總結(jié)
Picasso
獲取圖片資源并顯示的代碼流轉(zhuǎn)過程如下:
-
Picasso.with()
獲取Picasso實例 -
.load("url")
方法用傳入的url創(chuàng)建一個RequestCreator
對象 -
.into(imageview)
方法創(chuàng)建此次request
并將其封裝進action
再調(diào)用picasso.enqueueAndSubmit(action)
-
Picasso
類將action
對象交給dispatcher.submit()
-
dispatcher
類根據(jù)action
創(chuàng)建bitmapHunter
,并將bitmapHunter
提交至線程池執(zhí)行
當(dāng)bitmapHunter
獲取到圖片資源后,又經(jīng)過了以下步驟最終顯示在ImageView上
-
bitmapHunter
獲取圖片資源成功,調(diào)用dispatcher.dispatchComplete(this);
-
dispatcher
發(fā)送延遲200ms
、msg.what=HUNTER_DELAY_NEXT_BATCH
、攜帶200ms
內(nèi)完成的bitmapHunter
封裝為一個list的消息到主線程 - 主線程收到消息后,調(diào)用
Picasso
類的complete
方法,解析出bitmapHunter
中的action
-
action
的complete
方法內(nèi),將bitmap設(shè)置給Imageview
一次簡單的圖片加載雖然經(jīng)歷了這么多的步驟,但也換來了清晰的結(jié)構(gòu),強大的功能,良好的擴展性.而其中用到的設(shè)計模式也很值得學(xué)習(xí).