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