Picasso 是一款老牌的圖片加載器骗随,特別小巧般码,功能上雖然比不上 Glide 和 Fresco担锤。但是一般的圖片加載需求都能滿足。關(guān)鍵是 square 出品儿礼,JakeWharton 大神主導(dǎo)的項(xiàng)目咖杂,必屬精品,和自家的 OkHtttp 無縫銜接蚊夫。
分析版本: 2.5.2
Picasso.with(this)
.load("https://www.kaochong.com/static/imgs/ic_course_logo_92e76ec.png")
.into(imageView);
with()
看了幾個(gè)開源庫诉字,都是一個(gè)套路,先用門面模式提供一個(gè)單例給外部訪問知纷,這里是 Picasso壤圃,其他開源框架如 EventBus,Retrofit 都是一樣的琅轧。因?yàn)殚_源需要滿足很多 feature 避免不了使用一堆參數(shù)伍绳,建造者模式也是很常見的,幾乎每個(gè)開源庫必備乍桂。
public static Picasso with(Context context) {
if (singleton == null) {
synchronized (Picasso.class) {
if (singleton == null) {
singleton = new Builder(context).build();
}
}
}
return singleton;
}
load()
接著看 load 方法:
load 有 4 個(gè)重載方法:
load(Uri)
load(String)
load(File)
load(int)
分別對(duì)應(yīng)加載不同的來源冲杀。 這個(gè)方法會(huì)構(gòu)造一個(gè) RequestCreator
對(duì)象并返回。這個(gè) RequestCreator
看名字就知道睹酌,是負(fù)責(zé)創(chuàng)建圖片請(qǐng)求的权谁。RequestCreator
和 Request
的區(qū)別在于,Request
是最終創(chuàng)建完成的請(qǐng)求憋沿,所有關(guān)于圖片的信息都在這個(gè)請(qǐng)求里旺芽,包括圖片大小,圖片怎么轉(zhuǎn)換卤妒,圖片是否有漸變動(dòng)畫等等甥绿。而 RequestCreator
是一個(gè) Request
的生產(chǎn)者,負(fù)責(zé)把請(qǐng)求參數(shù)組合然后創(chuàng)建成一個(gè) Request
则披。
Picasso.with(this).load("url").placeholder()
.resize()
.transform()
.error()
.noFade()
.networkPolicy()
.centerCrop()
.into(imageview);
上面這段代碼中共缕,load()
返回的是 RequestCreator
對(duì)象,后面從 placeholder()
到 into()
都是 RequestCreator
的中的方法士复。直到在 into()
中才會(huì)把最終圖片請(qǐng)求 Request
對(duì)象構(gòu)造出來處理图谷。所以之前都是一堆參數(shù)的設(shè)置。
以 load(String)
為例看看內(nèi)部的操作:
public RequestCreator load(String path) {
if (path == null) {
return new RequestCreator(this, null, 0);
}
if (path.trim().length() == 0) {
throw new IllegalArgumentException("Path must not be empty.");
}
return load(Uri.parse(path));
}
load(String)
其實(shí)調(diào)用的是 load(Uri)
:
public RequestCreator load(Uri uri) {
return new RequestCreator(this, uri, 0);
}
RequestCreator 的構(gòu)造中阱洪,傳入了 picasso 實(shí)例便贵,用傳入的 Uri、resourceId冗荸、默認(rèn) Bitmap 參數(shù)在內(nèi)部構(gòu)造一個(gè) Request.Builder 實(shí)例承璃,用于拼接后續(xù)參數(shù)最終 build 出一個(gè) Request 實(shí)例。
RequestCreator(Picasso picasso, Uri uri, int resourceId) {
if (picasso.shutdown) {
throw new IllegalStateException(
"Picasso instance already shut down. Cannot submit new requests.");
}
this.picasso = picasso;
this.data = new Request.Builder(uri, resourceId, picasso.defaultBitmapConfig);
}
后面的 error()
蚌本、placeholder()
等等就很簡單了盔粹,就是把參數(shù)進(jìn)行賦值修改隘梨。
into()
關(guān)鍵的地方來了。
into 有 4 個(gè)重載方法:
into(Target)
into(RemoteViews,int,int,Notification)
into(RemoteViews,int,int[])
into(ImageView)
into(ImageView,Callback)
第 1 個(gè)用于實(shí)現(xiàn)了 Target 接口的對(duì)象舷嗡,第 2轴猎、3 用于 RemoteView 的加載,分別用于通知和桌面小部件进萄。4 和 5 就是我們常用的方法捻脖,把圖片加載到 ImageView, 區(qū)別是 5 有回調(diào)。這 5 個(gè)流程基本是一樣中鼠,我們就看 5 來看看加載的具體過程可婶。
public void into(ImageView target, Callback callback) {
// 獲取加載的開始時(shí)間,納秒級(jí)別的援雇,因?yàn)榧虞d很快的
long started = System.nanoTime();
// 檢查是否在主線程
checkMain();
// target 不能為空扰肌,不然沒法加載
if (target == null) {
throw new IllegalArgumentException("Target must not be null.");
}
// 沒圖片就設(shè)置占位圖
if (!data.hasImage()) {
picasso.cancelRequest(target);
if (setPlaceholder) {
setPlaceholder(target, getPlaceholderDrawable());
}
return;
}
// 如果是 fit 模式,圖片自適應(yīng)控件的大小熊杨,需要等 View layout 完確定寬和高再加載。這里采用的是監(jiān)聽 OnPreDraw 接口的方法盗舰。
if (deferred) {
// fit 模式不能指定圖片大小晶府,和 resize 沖突
if (data.hasSize()) {
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);
}
// 創(chuàng)建出最終的 Request
Request request = createRequest(started);
// 創(chuàng)建 Request key 用于緩存 Request
String requestKey = createKey(request);
// 首先從內(nèi)存中查找,內(nèi)存中有就把這個(gè)請(qǐng)求取消钻趋,直接從內(nèi)存加載
if (shouldReadFromMemoryCache(memoryPolicy)) {
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;
}
}
// 設(shè)置占位圖
if (setPlaceholder) {
setPlaceholder(target, getPlaceholderDrawable());
}
// 構(gòu)造出 Action
Action action =
new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
errorDrawable, requestKey, tag, callback, noFade);
// 將 Action 入隊(duì)執(zhí)行
picasso.enqueueAndSubmit(action);
}
into 中會(huì)檢查調(diào)用代碼是否在主線程川陆,因?yàn)橐?View,還有回調(diào)蛮位,肯定要在主線程较沪。然后判斷是否有圖片的源地址,如果給的是個(gè) null失仁,那么直接就終止請(qǐng)求了尸曼。如果設(shè)置了 fit 模式(自適應(yīng) ImageView 的寬和高),fit 模式和 resize 沖突萄焦,既然自適應(yīng)寬高了控轿,肯定就不能指定寬高。自適應(yīng) ImageView 的寬和高需要等待測量完成后得到寬高再繼續(xù)請(qǐng)求拂封,否則得到的寬高是 0茬射,Picasso 使用 ViewTreeObserver 監(jiān)聽 ImageView 的 OnPreDrawListener 接口來獲取寬和高,詳細(xì)的代碼可以看 DeferredRequestCreator
這個(gè)類冒签。
然后創(chuàng)建出最終的 Request在抛,此時(shí)的 Request 就代表了最終的圖片請(qǐng)求信息。然后沒有直接去請(qǐng)求萧恕,而是去緩存中查找刚梭,有的話就直接取消請(qǐng)求從內(nèi)存中加載肠阱。沒有的話就創(chuàng)建一個(gè) ImageViewAction
, 它是 Action
的子類。加載到不同的 Target 會(huì)使用不同的 Action望浩。加載到 Target
使用 TargetAction
辖所。加載到通知就使用 NotificationAction
∧サ拢可以去其他的 into
方法中查看源碼缘回。
Action
是一個(gè)抽象類, 內(nèi)部封裝了圖片的請(qǐng)求信息典挑,以及當(dāng)前圖片請(qǐng)求的其他參數(shù)(緩存策略酥宴,網(wǎng)絡(luò)策略,是否取消了請(qǐng)求您觉,Tag, 是否有動(dòng)畫等等)拙寡。需要子類實(shí)現(xiàn) 2 個(gè)方法:
// 解析圖片完成后拿到 Bitmap,子類定義如何顯示
abstract void complete(Bitmap result, VanGogh.LoadedFrom from);
// 解析發(fā)送錯(cuò)誤
abstract void error(Exception e);
這下可以理解它為啥叫 Action
了琳水,它需要子類自己處理 Bitmap肆糕。定義自己的 Action (行為), 成功拿到 Bitmap 怎么辦,發(fā)生錯(cuò)誤了怎么辦在孝?
ImageViewAction 的實(shí)現(xiàn)很簡單诚啃,內(nèi)部通過自定義 BitmapDrawable 來繪制自己的圖像,實(shí)現(xiàn)漸變私沮。加載錯(cuò)誤的時(shí)候就放置占位圖始赎。
接著看這最后一行
picasso.enqueueAndSubmit(action);
看看把 action
扔到哪去處理了。
void enqueueAndSubmit(Action action) {
Object target = action.getTarget();
if (target != null && targetToAction.get(target) != action) {
// 取消原來 target 的 action仔燕,將新的 action 存入
cancelExistingRequest(target);
targetToAction.put(target, action);
}
submit(action);
}
void submit(Action action) {
dispatcher.dispatchSubmit(action);
}
void dispatchSubmit(Action action) {
handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));
}
void performSubmit(Action action, boolean dismissFailed) {
// 處理暫停的請(qǐng)求
if (pausedTags.contains(action.getTag())) {
pausedActions.put(action.getTarget(), action);
if (action.getPicasso().loggingEnabled) {
log(OWNER_DISPATCHER, VERB_PAUSED, action.request.logId(),
"because tag '" + action.getTag() + "' is paused");
}
return;
}
// 將 action 合并造垛,action 的 key 是根據(jù) Request 中圖片參數(shù)生成的,這里的
// 意思就是如果圖片請(qǐng)求完全一樣晰搀,只是 Action 不一樣五辽,只需要請(qǐng)求一次拿到
// Bitmap 就行,因?yàn)閳D片信息完全相同厕隧,一個(gè) Request 對(duì)應(yīng)了對(duì)個(gè) Action
BitmapHunter hunter = hunterMap.get(action.getKey());
if (hunter != null) {
hunter.attach(action);
return;
}
if (service.isShutdown()) {
if (action.getPicasso().loggingEnabled) {
log(OWNER_DISPATCHER, VERB_IGNORED, action.request.logId(), "because shut down");
}
return;
}
// 構(gòu)造出 hunter
hunter = forRequest(action.getPicasso(), this, cache, stats, action);
// 扔給線程池執(zhí)行并獲得結(jié)果
hunter.future = service.submit(hunter);
// 緩存 hunter
hunterMap.put(action.getKey(), hunter);
// 是否移除請(qǐng)求失敗的 Action
if (dismissFailed) {
failedActions.remove(action.getTarget());
}
}
跟蹤可以發(fā)現(xiàn)交給 Dispatcher 中的 handler 處理了奔脐。
在 performSubmit()
中重點(diǎn)看 forRequest()
方法構(gòu)造出 BitmapHunter 實(shí)例。
static BitmapHunter forRequest(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats,
Action action) {
Request request = action.getRequest();
List<RequestHandler> requestHandlers = picasso.getRequestHandlers();
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);
}
forRequest()
中遍歷所有的 RequestHandler吁讨。誰能處理 Action 就處理這個(gè) Action髓迎。這是典型的責(zé)任鏈模式-
《JAVA與模式》之責(zé)任鏈模式。
在 Picasso 實(shí)例初始化的時(shí)候就把這些 RequestHandler 都加入了列表中建丧。
Picasso(Context context, Dispatcher dispatcher, Cache cache, Listener listener,
RequestTransformer requestTransformer, List<RequestHandler> extraRequestHandlers...) {
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));
allRequestHandlers.add(new MediaStoreRequestHandler(context));
allRequestHandlers.add(new ContentStreamRequestHandler(context));
allRequestHandlers.add(new AssetRequestHandler(context));
allRequestHandlers.add(new FileRequestHandler(context));
allRequestHandlers.add(new NetworkRequestHandler(dispatcher.downloader, stats));
requestHandlers = Collections.unmodifiableList(allRequestHandlers);
}
每個(gè) RequestHandler 重寫 canHandleRequest
來表明自己能處理哪種請(qǐng)求排龄。
BitmapHunter 是一個(gè) Runnable
, 構(gòu)造之后交給線程池處理。來看看 BitmapHunter 的 run()
。
@Override public void run() {
try {
updateThreadName(data);
// 解析圖片得到 Bitmap
result = hunt();
// 由 dispatcher 分發(fā)解析圖片的結(jié)果橄维。
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);
}
}
首先由 hunt()
方法解析出 Bitmap尺铣,再把解析后的結(jié)果交給 Dispatcher 來分發(fā),成功了咋樣争舞,失敗了咋樣凛忿,失敗了是否重試。Dispatcher 在 Picasso 中扮演了重要的角色竞川,負(fù)責(zé)整個(gè)流程的調(diào)度店溢。
看看 hunt() 是怎么解析出 Bitmap 的。首先還是從內(nèi)存中取委乌,每個(gè) RequestHandler 對(duì)象都持有了下載器床牧,用于下載網(wǎng)絡(luò)圖片。網(wǎng)絡(luò)圖片下載完是一個(gè)流需要解析成 Bitmap遭贸,非網(wǎng)絡(luò)的就直接得到一個(gè) Bitmap戈咳。最后在處理變換操作得到最終的 bitmap。
Bitmap hunt() throws IOException {
Bitmap bitmap = null;
// 從內(nèi)存緩存中取
if (shouldReadFromMemoryCache(memoryPolicy)) {
bitmap = cache.get(key);
if (bitmap != null) {
// 統(tǒng)計(jì) 緩存命中
stats.dispatchCacheHit();
loadedFrom = MEMORY;
return bitmap;
}
}
data.networkPolicy = retryCount == 0 ? NetworkPolicy.OFFLINE.index : networkPolicy;
// 用下載器請(qǐng)求url得到結(jié)果
RequestHandler.Result result = requestHandler.load(data, networkPolicy);
if (result != null) {
loadedFrom = result.getLoadedFrom();
exifRotation = result.getExifOrientation();
bitmap = result.getBitmap();
// 從流中解析出 Bitmap
if (bitmap == null) {
InputStream is = result.getStream();
try {
bitmap = decodeStream(is, data);
} finally {
Utils.closeQuietly(is);
}
}
}
if (bitmap != null) {
// 解碼
stats.dispatchBitmapDecoded(bitmap);
if (data.needsTransformation() || exifRotation != 0) {
// 同一時(shí)間只處理一個(gè) bitmap
synchronized (DECODE_LOCK) {
if (data.needsMatrixTransform() || exifRotation != 0) {
bitmap = transformResult(data, bitmap, exifRotation);
}
if (data.hasCustomTransformations()) {
bitmap = applyCustomTransformations(data.transformations, bitmap);
}
}
}
}
return bitmap;
}
Dispatcher 內(nèi)部實(shí)例化了一個(gè) HandlerThread壕吹,所有的調(diào)度都是通過這個(gè)子線程上執(zhí)行著蛙,通過這個(gè)子線程的 Handler 和 主線程的 Handler 以及線程池互相通信。
解析圖片的得到 Bitmap 后耳贬,Dispatcher 會(huì)調(diào)度到 dispatchComplete
册踩,跟蹤代碼走到 performComplete
。
void performComplete(BitmapHunter hunter) {
// 是否寫入內(nèi)存緩存
if (shouldWriteToMemoryCache(hunter.getMemoryPolicy())) {
cache.set(hunter.getKey(), hunter.getResult());
}
hunterMap.remove(hunter.getKey());
// 批處理 hunter
batch(hunter);
}
// 執(zhí)行批處理
void performBatchComplete() {
List<BitmapHunter> copy = new ArrayList<BitmapHunter>(batch);
batch.clear();
mainThreadHandler.sendMessage(mainThreadHandler.obtainMessage(HUNTER_BATCH_COMPLETE, copy));
logBatch(copy);
}
最終將一批 BitmapHunter 打包一起扔給主線程處理效拭。跟蹤代碼到 Picasso
類中的主線程的 Handler, 遍歷執(zhí)行 complete(hunter)
@SuppressWarnings("unchecked") List<BitmapHunter> batch = (List<BitmapHunter>) msg.obj;
//noinspection ForLoopReplaceableByForEach
for (int i = 0, n = batch.size(); i < n; i++) {
BitmapHunter hunter = batch.get(i);
hunter.picasso.complete(hunter);
}
complete(hunter)
中將調(diào)用 Action
的 complete
/error
方法進(jìn)行最后一步把 Bitmap 顯示到 target 上,并進(jìn)行相應(yīng)的成功或者失敗回調(diào)胖秒。
總結(jié)
引用一下blog.happyhls.me的圖(自己懶得畫了%>_<%)缎患,上面的流程可以總結(jié)成:
看源碼的過程中發(fā)現(xiàn) Dispatcher 里面一堆 handler send message,和 ActivityThread 中 H 和 AMS 通信很像阎肝,都用 Handler 來進(jìn)行通信挤渔。Handler 真是 Android 的精髓。