我每周會(huì)寫(xiě)一篇源代碼分析的文章,以后也可能會(huì)有其他主題.
如果你喜歡我寫(xiě)的文章的話,歡迎關(guān)注我的新浪微博@達(dá)達(dá)達(dá)達(dá)sky
地址: http://weibo.com/u/2030683111
每周我會(huì)第一時(shí)間在微博分享我寫(xiě)的文章,也會(huì)積極轉(zhuǎn)發(fā)更多有用的知識(shí)給大家.謝謝關(guān)注_,說(shuō)不定什么時(shí)候會(huì)有福利哈.
1.簡(jiǎn)介
Picasso是Square公司開(kāi)源的一個(gè)Android平臺(tái)上的圖片加載框架,也是大名鼎鼎的JakeWharton的代表作品之一.對(duì)于圖片加載和緩存框架,優(yōu)秀的開(kāi)源作品有不少。比如:Android-Universal-Image-Loader,Glide,fresco等等.我自己有在項(xiàng)目中使用過(guò)的有Picasso
,U-I-L
,Glide
.對(duì)于一般的應(yīng)用上面這些圖片加載和緩存框架都是能滿足使用的,Trinea有一篇關(guān)于這些框架的對(duì)比文章Android 三大圖片緩存原理蛤吓、特性對(duì)比.有興趣了解的可以去看看,本文我們主要講Picasso
的使用方法和源碼分析.
2.使用方法
//加載一張圖片
Picasso.with(this).load("url").placeholder(R.mipmap.ic_default).into(imageView);
//加載一張圖片并設(shè)置一個(gè)回調(diào)接口
Picasso.with(this).load("url").placeholder(R.mipmap.ic_default).into(imageView, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
}
});
//預(yù)加載一張圖片
Picasso.with(this).load("url").fetch();
//同步加載一張圖片,注意只能在子線程中調(diào)用并且Bitmap不會(huì)被緩存到內(nèi)存里.
new Thread() {
@Override
public void run() {
try {
final Bitmap bitmap = Picasso.with(getApplicationContext()).load("url").get();
mHandler.post(new Runnable() {
@Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
//加載一張圖片并自適應(yīng)imageView的大小,如果imageView設(shè)置了wrap_content,會(huì)顯示不出來(lái).直到該ImageView的
//LayoutParams被設(shè)置而且調(diào)用了該View的ViewTreeObserver.OnPreDrawListener回調(diào)接口后才會(huì)顯示.
Picasso.with(this).load("url").priority(Picasso.Priority.HIGH).fit().into(imageView);
//加載一張圖片并按照指定尺寸以centerCrop()的形式縮放.
Picasso.with(this).load("url").resize(200,200).centerCrop().into(imageView);
//加載一張圖片并按照指定尺寸以centerInside()的形式縮放.并設(shè)置加載的優(yōu)先級(jí)為高.注意centerInside()或centerCrop()
//只能同時(shí)使用一種,而且必須指定resize()或者resizeDimen();
Picasso.with(this).load("url").resize(400,400).centerInside().priority(Picasso.Priority.HIGH).into(imageView);
//加載一張圖片旋轉(zhuǎn)并且添加一個(gè)Transformation,可以對(duì)圖片進(jìn)行各種變化處理,例如圓形頭像.
Picasso.with(this).load("url").rotate(10).transform(new Transformation() {
@Override
public Bitmap transform(Bitmap source) {
//處理Bitmap
return null;
}
@Override
public String key() {
return null;
}
}).into(imageView);
//加載一張圖片并設(shè)置tag,可以通過(guò)tag來(lái)暫定或者繼續(xù)加載,可以用于當(dāng)ListView滾動(dòng)是暫定加載.停止?jié)L動(dòng)恢復(fù)加載.
Picasso.with(this).load("url").tag(mContext).into(imageView);
Picasso.with(this).pauseTag(mContext);
Picasso.with(this).resumeTag(mContxt);
上面我們介紹了Picasso
的大部分常用的使用方法.此外Picasso
內(nèi)部還具有監(jiān)控功能.可以檢測(cè)內(nèi)存數(shù)據(jù),緩存命中率等等.而且還會(huì)根據(jù)網(wǎng)絡(luò)變化優(yōu)化并發(fā)線程.下面我們就來(lái)進(jìn)行Picasso
的源碼分析。這里說(shuō)明一下,Picasso
的源碼分析目前在網(wǎng)絡(luò)上已經(jīng)有幾篇比較好的分析文章,我在分析的時(shí)候也借鑒了不少,分別是RowandJJ的Picasso源碼學(xué)習(xí)和閉門(mén)造車的Picasso源碼分析系列.在這里注明,下文章有部分圖是引用自這兩個(gè)地方的.引用就不做具體標(biāo)注了.
3.類關(guān)系圖
從類圖上我們可以看出
Picasso
的核心類主要包括:Picasso
,RequestCreator
,Action
,Dispatcher
,Request
,RequestHandler
,BitmapHunter
等等.一張圖片加載可以分為以下幾步:
創(chuàng)建->入隊(duì)->執(zhí)行->解碼->變換->批處理->完成->分發(fā)->顯示(可選)
下面就讓我們來(lái)通過(guò)Picasso
的調(diào)用流程來(lái)具體分析它的具體實(shí)現(xiàn).
4.源碼分析
Picasso.with()方法的實(shí)現(xiàn)
按照我們的慣例,我們從Picasso
的調(diào)用流程開(kāi)始分析,我們就從加載一張圖片開(kāi)始看起:
Picasso.with(this).load(url).into(imageView);
讓我們先來(lái)看看Picasso.with()
做了什么:
public static Picasso with(Context context) {
if (singleton == null) {
synchronized (Picasso.class) {
if (singleton == null) {
singleton = new Builder(context).build();
}
}
}
return singleton;
}
維護(hù)一個(gè)Picasso
的單例,如果還未實(shí)例化就通過(guò)new Builder(context).build()
創(chuàng)建一個(gè)singleton
并返回,我們繼續(xù)看Builder
類的實(shí)現(xiàn):
public static class Builder {
public Builder(Context context) {
if (context == null) {
throw new IllegalArgumentException("Context must not be null.");
}
this.context = context.getApplicationContext();
}
/** Create the {@link Picasso} instance. */
public Picasso build() {
Context context = this.context;
if (downloader == null) {
//創(chuàng)建默認(rèn)下載器
downloader = Utils.createDefaultDownloader(context);
}
if (cache == null) {
//創(chuàng)建Lru內(nèi)存緩存
cache = new LruCache(context);
}
if (service == null) {
//創(chuàng)建線程池,默認(rèn)有3個(gè)執(zhí)行線程,會(huì)根據(jù)網(wǎng)絡(luò)狀況自動(dòng)切換線程數(shù)
service = new PicassoExecutorService();
}
if (transformer == null) {
//創(chuàng)建默認(rèn)的transformer,并無(wú)實(shí)際作用
transformer = RequestTransformer.IDENTITY;
}
//創(chuàng)建stats用于統(tǒng)計(jì)緩存,以及緩存命中率,下載數(shù)量等等
Stats stats = new Stats(cache);
//創(chuàng)建dispatcher對(duì)象用于任務(wù)的調(diào)度
Dispatcher dispatcher = new Dispatcher(context, service, HANDLER, downloader, cache, stats);
return new Picasso(context, dispatcher, cache, listener, transformer, requestHandlers, stats,
defaultBitmapConfig, indicatorsEnabled, loggingEnabled);
}
}
上面的代碼里省去了部分配置的方法,當(dāng)我們使用Picasso
默認(rèn)配置的時(shí)候(當(dāng)然也可以自定義),最后會(huì)調(diào)用build()
方法并配置好我們需要的各種對(duì)象,最后實(shí)例化一個(gè)Picasso
對(duì)象并返回。最后在Picasso
的構(gòu)造方法里除了對(duì)這些對(duì)象的賦值以及創(chuàng)建一些新的對(duì)象,例如清理線程等等.最重要的是初始化了requestHandlers
,下面是代碼片段:
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);
可以看到除了添加我們可以自定義的extraRequestHandlers
,另外添加了7個(gè)RequestHandler
分別用來(lái)處理加載不同來(lái)源的資源,可能是Resource
里的,也可能是File
也可能是來(lái)源于網(wǎng)絡(luò)的資源.這里使用了一個(gè)ArrayList
來(lái)存放這些RequestHandler
現(xiàn)在先不用了解這么做是為什么,下面我們會(huì)分析,到這我們就了解了Picasso.with()
做了什么,接下來(lái)我們?nèi)タ纯?code>load()方法.
load(),centerInside(),等方法的實(shí)現(xiàn)
在Picasso
的load()
方法里我們可以傳入String
,Uri
或者File
對(duì)象,但是其最終都是返回一個(gè)RequestCreator
對(duì)象,如下所示:
public RequestCreator load(Uri uri) {
return new RequestCreator(this, uri, 0);
}
再來(lái)看看RequestCreator
的構(gòu)造方法:
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);
}
首先是持有一個(gè)Picasso
的對(duì)象,然后構(gòu)建一個(gè)Request
的Builder
對(duì)象,將我們需要加載的圖片的信息都保存在data
里,在我們通過(guò).centerCrop()
或者.transform()
等等方法的時(shí)候?qū)嶋H上也就是改變data
內(nèi)的對(duì)應(yīng)的變量標(biāo)識(shí),再到處理的階段根據(jù)這些參數(shù)來(lái)進(jìn)行對(duì)應(yīng)的操作,所以在我們調(diào)用into()
方法之前,所有的操作都是在設(shè)定我們需要處理的參數(shù),真正的操作都是有into()
方法引起的。
into()方法的實(shí)現(xiàn)
從上文中我們知道在我們調(diào)用了load()
方法之后會(huì)返回一個(gè)RequestCreator
對(duì)象,所以.into(imageView)
方法必然是在RequestCreator
里:
public void into(ImageView target) {
//傳入空的callback
into(target, null);
}
public void into(ImageView target, Callback callback) {
long started = System.nanoTime();
//檢查調(diào)用是否在主線程
checkMain();
if (target == null) {
throw new IllegalArgumentException("Target must not be null.");
}
//如果沒(méi)有設(shè)置需要加載的uri,或者resourceId
if (!data.hasImage()) {
picasso.cancelRequest(target);
//如果設(shè)置占位圖片,直接加載并返回
if (setPlaceholder) {
setPlaceholder(target, getPlaceholderDrawable());
}
return;
}
//如果是延時(shí)加載,也就是選擇了fit()模式
if (deferred) {
//fit()模式是適應(yīng)target的寬高加載,所以并不能手動(dòng)設(shè)置resize,如果設(shè)置就拋出異常
if (data.hasSize()) {
throw new IllegalStateException("Fit cannot be used with resize.");
}
int width = target.getWidth();
int height = target.getHeight();
//如果目標(biāo)ImageView的寬或高現(xiàn)在為0
if (width == 0 || height == 0) {
//先設(shè)置占位符
if (setPlaceholder) {
setPlaceholder(target, getPlaceholderDrawable());
}
//監(jiān)聽(tīng)I(yíng)mageView的ViewTreeObserver.OnPreDrawListener接口,一旦ImageView
//的寬高被賦值,就按照ImageView的寬高繼續(xù)加載.
picasso.defer(target, new DeferredRequestCreator(this, target, callback));
return;
}
//如果ImageView有寬高就設(shè)置設(shè)置
data.resize(width, height);
}
//構(gòu)建Request
Request request = createRequest(started);
//構(gòu)建requestKey
String requestKey = createKey(request);
//根據(jù)memoryPolicy來(lái)決定是否可以從內(nèi)存里讀取
if (shouldReadFromMemoryCache(memoryPolicy)) {
//通過(guò)LruCache來(lái)讀取內(nèi)存里的緩存圖片
Bitmap bitmap = picasso.quickMemoryCacheCheck(requestKey);
//如果讀取到
if (bitmap != null) {
//取消target的request
picasso.cancelRequest(target);
//設(shè)置圖片
setBitmap(target, picasso.context, bitmap, MEMORY, noFade, picasso.indicatorsEnabled);
if (picasso.loggingEnabled) {
log(OWNER_MAIN, VERB_COMPLETED, request.plainId(), "from " + MEMORY);
}
//如果設(shè)置了回調(diào)接口就回調(diào)接口的方法.
if (callback != null) {
callback.onSuccess();
}
return;
}
}
//如果緩存里沒(méi)讀到,先根據(jù)是否設(shè)置了占位圖并設(shè)置占位
if (setPlaceholder) {
setPlaceholder(target, getPlaceholderDrawable());
}
//構(gòu)建一個(gè)Action對(duì)象,由于我們是往ImageView里加載圖片,所以這里創(chuàng)建的是一個(gè)ImageViewAction對(duì)象.
Action action =
new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
errorDrawable, requestKey, tag, callback, noFade);
//將Action對(duì)象入列提交
picasso.enqueueAndSubmit(action);
}
整個(gè)流程看下來(lái)應(yīng)該是比較清晰的,最后是創(chuàng)建了一個(gè)ImageViewAction
對(duì)象并通過(guò)picasso
提交,這里簡(jiǎn)要說(shuō)明一下ImageViewAction
,實(shí)際上Picasso
會(huì)根據(jù)我們調(diào)用的不同方式來(lái)實(shí)例化不同的Action
對(duì)象,當(dāng)我們需要往ImageView
里加載圖片的時(shí)候會(huì)創(chuàng)建ImageViewAction
對(duì)象,如果是往實(shí)現(xiàn)了Target
接口的對(duì)象里加載圖片是則會(huì)創(chuàng)建TargetAction
對(duì)象,這些Action
類的實(shí)現(xiàn)類不僅保存了這次加載需要的所有信息,還提供了加載完成后的回調(diào)方法.也是由子類實(shí)現(xiàn)并用來(lái)完成不同的調(diào)用的棱诱。然后讓我們繼續(xù)去看picasso.enqueueAndSubmit(action)
方法:
void enqueueAndSubmit(Action action) {
Object target = action.getTarget();
//取消這個(gè)target已經(jīng)有的action.
if (target != null && targetToAction.get(target) != action) {
// This will also check we are on the main thread.
cancelExistingRequest(target);
targetToAction.put(target, action);
}
//提交action
submit(action);
}
//調(diào)用dispatcher來(lái)派發(fā)action
void submit(Action action) {
dispatcher.dispatchSubmit(action);
}
很簡(jiǎn)單,最后是轉(zhuǎn)到了dispatcher
類來(lái)處理,那我們就來(lái)看看dispatcher.dispatchSubmit(action)
方法:
void dispatchSubmit(Action action) {
handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));
}
看到通過(guò)一個(gè)handler
對(duì)象發(fā)送了一個(gè)REQUEST_SUBMIT
的消息,那么這個(gè)handler
是存在與哪個(gè)線程的呢?
Dispatcher(Context context, ExecutorService service, Handler mainThreadHandler,
Downloader downloader, Cache cache, Stats stats) {
this.dispatcherThread = new DispatcherThread();
this.dispatcherThread.start();
this.handler = new DispatcherHandler(dispatcherThread.getLooper(), this);
this.mainThreadHandler = mainThreadHandler;
}
static class DispatcherThread extends HandlerThread {
DispatcherThread() {
super(Utils.THREAD_PREFIX + DISPATCHER_THREAD_NAME, THREAD_PRIORITY_BACKGROUND);
}
}
上面是Dispatcher
的構(gòu)造方法(省略了部分代碼),可以看到先是創(chuàng)建了一個(gè)HandlerThread
對(duì)象,然后創(chuàng)建了一個(gè)DispatcherHandler
對(duì)象,這個(gè)handler
就是剛剛用來(lái)發(fā)送REQUEST_SUBMIT
消息的handler
,這里我們就明白了原來(lái)是通過(guò)Dispatcher
類里的一個(gè)子線程里的handler
不斷的派發(fā)我們的消息,這里是用來(lái)派發(fā)我們的REQUEST_SUBMIT
消息,而且最終是調(diào)用了 dispatcher.performSubmit(action);
方法:
void performSubmit(Action action) {
performSubmit(action, true);
}
void performSubmit(Action action, boolean dismissFailed) {
//是否該tag的請(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;
}
//通過(guò)action的key來(lái)在hunterMap查找是否有相同的hunter,這個(gè)key里保存的是我們
//的uri或者resourceId和一些參數(shù),如果都是一樣就將這些action合并到一個(gè)
//BitmapHunter里去.
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;
}
//創(chuàng)建BitmapHunter對(duì)象
hunter = forRequest(action.getPicasso(), this, cache, stats, action);
//通過(guò)service執(zhí)行hunter并返回一個(gè)future對(duì)象
hunter.future = service.submit(hunter);
//將hunter添加到hunterMap中
hunterMap.put(action.getKey(), hunter);
if (dismissFailed) {
failedActions.remove(action.getTarget());
}
if (action.getPicasso().loggingEnabled) {
log(OWNER_DISPATCHER, VERB_ENQUEUED, action.request.logId());
}
}
注釋很詳細(xì),這里我們?cè)俜治鲆幌?code>forRequest()是如何實(shí)現(xiàn)的:
static BitmapHunter forRequest(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats,
Action action) {
Request request = action.getRequest();
List<RequestHandler> requestHandlers = picasso.getRequestHandlers();
//從requestHandlers中檢測(cè)哪個(gè)RequestHandler可以處理這個(gè)request,如果找到就創(chuàng)建
//BitmapHunter并返回.
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);
}
這里就體現(xiàn)出來(lái)了責(zé)任鏈模式,通過(guò)依次調(diào)用requestHandlers
里RequestHandler
的canHandleRequest()
方法來(lái)確定這個(gè)request
能被哪個(gè)RequestHandler
執(zhí)行,找到對(duì)應(yīng)的RequestHandler
后就創(chuàng)建BitmapHunter
對(duì)象并返回.再回到performSubmit()
方法里,通過(guò)service.submit(hunter);
執(zhí)行了hunter
,hunter
實(shí)現(xiàn)了Runnable
接口,所以run()
方法就會(huì)被執(zhí)行,所以我們繼續(xù)看看BitmapHunter
里run()
方法的實(shí)現(xiàn):
@Override public void run() {
try {
//更新當(dāng)前線程的名字
updateThreadName(data);
if (picasso.loggingEnabled) {
log(OWNER_HUNTER, VERB_EXECUTING, getLogIdsForHunter(this));
}
//調(diào)用hunt()方法并返回Bitmap類型的result對(duì)象.
result = hunt();
//如果為空,調(diào)用dispatcher發(fā)送失敗的消息,
//如果不為空則發(fā)送完成的消息
if (result == null) {
dispatcher.dispatchFailed(this);
} else {
dispatcher.dispatchComplete(this);
}
//通過(guò)不同的異常來(lái)進(jìn)行對(duì)應(yīng)的處理
} 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;
//是否可以從內(nèi)存中讀取
if (shouldReadFromMemoryCache(memoryPolicy)) {
bitmap = cache.get(key);
if (bitmap != null) {
//統(tǒng)計(jì)緩存命中率
stats.dispatchCacheHit();
loadedFrom = MEMORY;
if (picasso.loggingEnabled) {
log(OWNER_HUNTER, VERB_DECODED, data.logId(), "from cache");
}
return bitmap;
}
}
//如果未設(shè)置networkPolicy并且retryCount為0,則將networkPolicy設(shè)置為
//NetworkPolicy.OFFLINE
data.networkPolicy = retryCount == 0 ? NetworkPolicy.OFFLINE.index : networkPolicy;
//通過(guò)對(duì)應(yīng)的requestHandler來(lái)獲取result
RequestHandler.Result result = requestHandler.load(data, networkPolicy);
if (result != null) {
loadedFrom = result.getLoadedFrom();
exifOrientation = 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);
//處理Transformation
if (data.needsTransformation() || exifOrientation != 0) {
synchronized (DECODE_LOCK) {
if (data.needsMatrixTransform() || exifOrientation != 0) {
bitmap = transformResult(data, bitmap, exifOrientation);
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);
}
}
}
//返回bitmap
return bitmap;
}
在run()
方法里調(diào)用了hunt()
方法來(lái)獲取result
然后通知了dispatcher
來(lái)處理結(jié)果,并在try-catch
里通知dispatcher
來(lái)處理相應(yīng)的異常,在hunt()
方法里通過(guò)前面指定的requestHandler
來(lái)獲取相應(yīng)的result
,我們是從網(wǎng)絡(luò)加載圖片,自然是調(diào)用NetworkRequestHandler
的load()
方法來(lái)處理我們的request
,這里我們就不再分析NetworkRequestHandler
具體的細(xì)節(jié).獲取到result
之后就獲得我們的bitmap
然后檢測(cè)是否需要Transformation
,這里使用了一個(gè)全局鎖DECODE_LOCK
來(lái)保證同一個(gè)時(shí)刻僅僅有一個(gè)圖片正在處理。我們假設(shè)我們的請(qǐng)求被正確處理了,這樣我們拿到我們的result
然后調(diào)用了dispatcher.dispatchComplete(this);
最終也是通過(guò)handler
調(diào)用了dispatcher.performComplete()
方法:
void performComplete(BitmapHunter hunter) {
//是否可以放入內(nèi)存緩存里
if (shouldWriteToMemoryCache(hunter.getMemoryPolicy())) {
cache.set(hunter.getKey(), hunter.getResult());
}
//從hunterMap移除
hunterMap.remove(hunter.getKey());
//處理hunter
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)) {
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);
}
首先是添加到內(nèi)存緩存中去,然后在發(fā)送一個(gè)HUNTER_DELAY_NEXT_BATCH
消息,實(shí)際上這個(gè)消息最后會(huì)出發(fā)performBatchComplete()
方法,performBatchComplete()
里則是通過(guò)mainThreadHandler
將BitmapHunter
的List
發(fā)送到主線程處理,所以我們?nèi)タ纯?code>mainThreadHandler的handleMessage()
方法:
static final Handler HANDLER = new Handler(Looper.getMainLooper()) {
@Override public void handleMessage(Message msg) {
switch (msg.what) {
case HUNTER_BATCH_COMPLETE: {
@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);
}
break;
}
default:
throw new AssertionError("Unknown handler message received: " + msg.what);
}
}
};
很簡(jiǎn)單,就是依次調(diào)用picasso.complete(hunter)
方法:
void complete(BitmapHunter hunter) {
//獲取單個(gè)Action
Action single = hunter.getAction();
//獲取被添加進(jìn)來(lái)的Action
List<Action> joined = hunter.getActions();
//是否有合并的Action
boolean hasMultiple = joined != null && !joined.isEmpty();
//是否需要派發(fā)
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();
//派發(fā)Action
if (single != null) {
deliverAction(result, from, single);
}
//派發(fā)合并的Action
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.");
}
//回調(diào)action的complete()方法
action.complete(result, from);
if (loggingEnabled) {
log(OWNER_MAIN, VERB_COMPLETED, action.request.logId(), "from " + from);
}
} else {
//失敗則回調(diào)error()方法
action.error();
if (loggingEnabled) {
log(OWNER_MAIN, VERB_ERRORED, action.request.logId());
}
}
}
可以看出最終是回調(diào)了action
的complete()
方法,從前文知道我們這里是ImageViewAction
,所以我們?nèi)タ纯?code>ImageViewAction的complete()
的實(shí)現(xiàn):
@Override public void complete(Bitmap result, Picasso.LoadedFrom from) {
if (result == null) {
throw new AssertionError(
String.format("Attempted to complete action with no result!\n%s", this));
}
//得到target也就是ImageView
ImageView target = this.target.get();
if (target == null) {
return;
}
Context context = picasso.context;
boolean indicatorsEnabled = picasso.indicatorsEnabled;
//通過(guò)PicassoDrawable來(lái)將bitmap設(shè)置到ImageView上
PicassoDrawable.setBitmap(target, context, result, from, noFade, indicatorsEnabled);
//回調(diào)callback接口
if (callback != null) {
callback.onSuccess();
}
}
很顯然通過(guò)了PicassoDrawable.setBitmap()
將我們的Bitmap
設(shè)置到了我們的ImageView
上,最后并回調(diào)callback
接口,這里為什么會(huì)使用PicassoDrawabl
來(lái)設(shè)置Bitmap
呢?使用過(guò)Picasso
的都知道,Picasso
自帶漸變的加載動(dòng)畫(huà),所以這里就是處理漸變動(dòng)畫(huà)的地方,由于篇幅原因我們就不做具體分析了,感興趣的同學(xué)可以自行研究,所以到這里我們的整個(gè)Picasso
的調(diào)用流程的源碼分析就結(jié)束了.
5.設(shè)計(jì)模式
建造者模式
建造者模式是指:將一個(gè)復(fù)雜對(duì)象的構(gòu)建與它的表示分離,使得同樣的構(gòu)建過(guò)程可以創(chuàng)建不同的表示蘸嘶。建造者模式應(yīng)該是我們都比較熟悉的一種模式,在創(chuàng)建AlertDialog
的時(shí)候通過(guò)配置不同的參數(shù)就可以展示不同的AlertDialog
,這也正是建造者模式的用途,通過(guò)不同的參數(shù)配置或者不同的執(zhí)行順序來(lái)構(gòu)建不同的對(duì)象,在Picasso
里當(dāng)構(gòu)建RequestCreator
的時(shí)候正是使用了這種設(shè)計(jì)模式,我們通過(guò)可選的配置比如centerInside()
,placeholder()
等等來(lái)分別達(dá)到不同的使用方式,在這種使用場(chǎng)景下使用建造者模式是非常合適的.
責(zé)任鏈模式
責(zé)任鏈模式是指:一個(gè)請(qǐng)求沿著一條“鏈”傳遞,直到該“鏈”上的某個(gè)處理者處理它為止陪汽。當(dāng)我們有一個(gè)請(qǐng)求可以被多個(gè)處理者處理或處理者未明確指定時(shí)训唱。可以選擇使用責(zé)任鏈模式,在Picasso
里當(dāng)我們通過(guò)BitmapHunter
的forRequest()
方法構(gòu)建一個(gè)BitmapHunter
對(duì)象時(shí),需要為Request
指定一個(gè)對(duì)應(yīng)的RequestHandler
來(lái)進(jìn)行處理Request
.這里就使用了責(zé)任鏈模式,依次調(diào)用requestHandler.canHandleRequest(request)
方法來(lái)判斷是否該RequestHandler
能處理該Request
如果可以就構(gòu)建一個(gè)RequestHandler
對(duì)象返回.這里就是典型的責(zé)任鏈思想的體現(xiàn)掩缓。
6.個(gè)人評(píng)價(jià)
Picasso
是我最早接觸Android時(shí)第一個(gè)使用的圖片加載庫(kù),當(dāng)時(shí)也了解過(guò)U-I-L
,但是最終選擇使用了Picasso
因?yàn)閷?duì)于當(dāng)時(shí)的我來(lái)說(shuō)Picasso
使用起來(lái)足夠簡(jiǎn)單,簡(jiǎn)單到我根本不需要任何配置一行代碼就可以搞定圖片加載,所以對(duì)于初學(xué)者Picasso
可以算得上最易使用的圖片加載緩存庫(kù)了,而且分析完源代碼發(fā)現(xiàn)Picasso
實(shí)現(xiàn)的feature
并不算少,對(duì)于一個(gè)標(biāo)準(zhǔn)的圖片庫(kù)功能也可謂是應(yīng)有竟有,雖然比Glide
和Fresco
是少一些功能或者性能,但是作為出現(xiàn)時(shí)間比較早的圖片加載庫(kù)還是值得推薦學(xué)習(xí)和使用的雪情。