以下是picasso調(diào)用的圖解:
1.當(dāng)我們?cè)谡{(diào)用Picasso.with()方法的時(shí)候鹦牛,會(huì)生成一個(gè)單例的Picasso
public static Picasso with(Context context) {
if (singleton == null) {
synchronized (Picasso.class) {
if (singleton == null) {
singleton = new Builder(context).build();
}
}
}
return singleton;
}
首先是全局的一個(gè)單例對(duì)象蒜焊,其次是通過(guò)Builder模式生成對(duì)應(yīng)的Picasso對(duì)象迂尝。
2.我們?cè)谡{(diào)用完上面的方法之后嘉熊,會(huì)繼續(xù)調(diào)用load方法:
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));
}
支持loadFile陈惰,Uri北专,path等禀挫,在這里會(huì)其實(shí)最終都是調(diào)用load(uri)的方法,生成RequestCreator拓颓,接下來(lái)的placeHolder语婴,errImage,設(shè)置圖片等,通過(guò)鏈?zhǔn)秸{(diào)用實(shí)現(xiàn)砰左。
3.在創(chuàng)建完成RequestCreator之后匿醒,我們會(huì)執(zhí)行RequestCreator的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()) {//1
picasso.cancelRequest(target);
if (setPlaceholder) {
setPlaceholder(target, getPlaceholderDrawable());
}
return;
}
if (deferred) {
if (data.hasSize()) {//2
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);
String requestKey = createKey(request);
if (shouldReadFromMemoryCache(memoryPolicy)) {//3
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) {//4
setPlaceholder(target, getPlaceholderDrawable());
}
Action action =
new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
errorDrawable, requestKey, tag, callback, noFade);
picasso.enqueueAndSubmit(action);//5
}
在這里主要就是執(zhí)行圖片的獲取,轉(zhuǎn)換大小以及圖片的顯示的操作缠导。
3.1 上面的第一步主要是判斷有沒(méi)有資源文件設(shè)置或者本地路徑等廉羔,如果有那么直接顯示,這里主要是變相地實(shí)現(xiàn)了Picasso的本地圖片的加載的實(shí)現(xiàn)僻造。
3.2 第二步設(shè)置要顯示的ImageView控件的大小憋他,以便計(jì)算圖片和控件的大小比,以進(jìn)行加載時(shí)候內(nèi)存的優(yōu)化
3.3 第三步會(huì)從內(nèi)存中去讀取圖片髓削,讀取到圖片增加命中的計(jì)算器
3.4 第四步是設(shè)置空白圖片
3.5 第五步主要就是執(zhí)行圖片的獲取操作竹挡,picasso.enqueueAndSubmit(Action)方法:
4.picasso.enqueueAndSubmit(Action)方法:
void enqueueAndSubmit(Action action) {
Object target = action.getTarget();//因?yàn)樵谏厦娴奈覀兂跏蓟腎mageView的Action,所以target是要加載的ImageView蔬螟。
if (target != null && targetToAction.get(target) != action) {
// This will also check we are on the main thread.
cancelExistingRequest(target);
targetToAction.put(target, action);
}
submit(action);
}
在這里我們會(huì)調(diào)用submit方法此迅,該方法主要是將action時(shí)間分發(fā)給對(duì)應(yīng)的Dispatcher,dispatcher.dispatchSubmit(action);
void dispatchSubmit(Action action) {
handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));
}
對(duì)應(yīng)的會(huì)通過(guò)Handler發(fā)送一個(gè)REQUEST_SUBMIT的消息旧巾,這個(gè)Handler是DispatcherHandler的實(shí)例對(duì)象耸序,執(zhí)行對(duì)應(yīng)的HandleMessage方法,
case REQUEST_SUBMIT: {
Action action = (Action) msg.obj;
dispatcher.performSubmit(action);
break;
}
5.我們來(lái)看看Dispatcher類的performSubmit方法:
void performSubmit(Action action, boolean dismissFailed) {
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;
}
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;
}
hunter = forRequest(action.getPicasso(), this, cache, stats, action);//1
hunter.future = service.submit(hunter);
hunterMap.put(action.getKey(), hunter);
if (dismissFailed) {
failedActions.remove(action.getTarget());
}
if (action.getPicasso().loggingEnabled) {
log(OWNER_DISPATCHER, VERB_ENQUEUED, action.request.logId());
}
}
注釋1中會(huì)一次調(diào)用各種RequestHandler的canHandleRequest方法鲁猩,來(lái)選擇能處理的RequestHandler
piassco在初始化的時(shí)候坎怪,默認(rèn)會(huì)添加如下的RequestHandler
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));
6.上述找到對(duì)應(yīng)能處理的RequestHandler之后,創(chuàng)建對(duì)應(yīng)的bitmapHunter廓握,BitmapHunder其實(shí)是Runnable的實(shí)現(xiàn)搅窿。
@Override
public Future<?> submit(Runnable task) {
PicassoFutureTask ftask = new PicassoFutureTask((BitmapHunter) task);
execute(ftask);
return ftask;
}
創(chuàng)建對(duì)應(yīng)的Runnable完成之后,加入線程池中執(zhí)行
@Override public void run() {
try {
updateThreadName(data);
if (picasso.loggingEnabled) {
log(OWNER_HUNTER, VERB_EXECUTING, getLogIdsForHunter(this));
}
result = hunt();//1
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);
}
}
注釋1是獲取圖片的邏輯
Bitmap hunt() throws IOException {
Bitmap bitmap = null;
if (shouldReadFromMemoryCache(memoryPolicy)) {//1
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);
if (result != null) {//2
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) {//3
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;
}
上述注釋1就是從內(nèi)存中獲取圖片隙券,如果取不到圖片注釋2由RequestHandler.load拿到圖片數(shù)據(jù)的流的結(jié)果對(duì)象男应,然后解析成圖片,注釋3在拿到圖片之后娱仔,對(duì)圖片根據(jù)控件的大小進(jìn)行轉(zhuǎn)換沐飘。拿到圖片之后,發(fā)送消息code為HUNTER_COMPLETE的消息到MessageQueue中牲迫,
if (result == null) {
dispatcher.dispatchFailed(this);
} else {
dispatcher.dispatchComplete(this);
}
接著dispatcherHandler執(zhí)行
case HUNTER_COMPLETE: {
BitmapHunter hunter = (BitmapHunter) msg.obj;
dispatcher.performComplete(hunter);
break;
}
void performComplete(BitmapHunter hunter) {
if (shouldWriteToMemoryCache(hunter.getMemoryPolicy())) {
cache.set(hunter.getKey(), hunter.getResult());
}
hunterMap.remove(hunter.getKey());
batch(hunter);//1
if (hunter.getPicasso().loggingEnabled) {
log(OWNER_DISPATCHER, VERB_BATCHED, getLogIdsForHunter(hunter), "for completion");
}
}
進(jìn)行內(nèi)存中保存耐朴。完成圖片的內(nèi)存緩存之后,就是對(duì)圖片設(shè)置到ImageView上盹憎,Dispatch的batch方法
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);
}
}
case HUNTER_DELAY_NEXT_BATCH: {
dispatcher.performBatchComplete();
break;
}
void performBatchComplete() {
List<BitmapHunter> copy = new ArrayList<BitmapHunter>(batch);
batch.clear();
mainThreadHandler.sendMessage(mainThreadHandler.obtainMessage(HUNTER_BATCH_COMPLETE, copy));
logBatch(copy);
}
其實(shí)上面的操作是將io線程切換到主線程上來(lái)筛峭,到綁定主線程Looper的handler接收到消息,會(huì)執(zhí)行
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;
}
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);//1
}
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);
}
}
注釋1就是將圖片設(shè)置到Image的操作陪每。
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());
}
}
通過(guò)ImageViewAction執(zhí)行界面的設(shè)置操作影晓。
總結(jié)
上面其實(shí)只是一個(gè)源碼的閱讀流程記錄而已镰吵,其實(shí)其中的更多的是設(shè)計(jì)思想的理解,設(shè)計(jì)模式的學(xué)習(xí)等俯艰,比如這里的Action接口捡遍,多個(gè)子類實(shí)現(xiàn)了該接口,都會(huì)執(zhí)行compelete方法竹握,這就是策略模式的模型画株,會(huì)根據(jù)你傳入的是ImageViewAction還是GetAction來(lái)執(zhí)行對(duì)應(yīng)的complete,這樣就需要判斷是ImageViewAction還是GetAction來(lái)執(zhí)行對(duì)應(yīng)的操作啦辐;還有在初始化的時(shí)候谓传,會(huì)在list中增加各種RequestHandler,然后在根據(jù)你傳入的uri芹关,找到對(duì)應(yīng)的RequestHandler這種設(shè)計(jì)续挟,個(gè)人覺(jué)得這種設(shè)計(jì)在解決一個(gè)問(wèn)題有多種串行的嘗試的時(shí)候,這個(gè)還是很有用侥衬。
如果你們覺(jué)得文章對(duì)你有啟示作用诗祸,希望你們幫忙點(diǎn)個(gè)贊或者關(guān)注下,謝謝轴总。