Picasso.with(this).load("").placeholder(R.mipmap.ic_launcher).into(imageView);
這是一個Picasso的使用方式,從這里入手來看看Picasso的源碼構造方式
首先看一下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實例
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的實例對象
這里面主要做關于一些賦值操作,以及創建一些新的對象,例如清理線程等等.最重要的是初始化了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);
接下來就是調用load()方法傳入String,Uri或者File對象了
這里的load()方法均是創建了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);
}
而into()方法則是RequestCreator方法如下
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);
}
步驟如下:
1.檢查是否工作在主線程,如果不在則直接拋出異常退出
2.如果沒有Uri或者resoure Id,則取消該請求,并設置默認顯示圖片并退出
3.是否需要延遲執行,需要,則判斷是否設置過targetSize,如果已經設置過,則拋出異常退出,沒有設置過,則獲取target,即ImageView對應的長和寬,如果長和寬都是0,那么就設置默認的圖片,并構建一個DeferredRequestCreator,放入Picasso對應的隊列當中
4.創建Reqeust,生成requestKey
5.判斷是否需要跳過MemoryCache,如果不跳過,那么就嘗試獲取圖片,并取消對應的請求,進行回調。
6.沒有從緩存中獲取到,則據是否設置了占位圖并設置占位
7.生成對應的ImageViewAction,并將其添加到隊列中
接下來就是任務相關的調度了,通過代碼可以看到添加隊列后,經過調用調到Dispatcher的performSubmit方法如下
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
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());
}
}
上面創建的BitmapHunter實現了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();
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);
//處理Transformation
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.更新線程名稱
2.調用hunt()方法獲取請求結果
3.判斷是否跳過MemoryCache,如果不跳過,那么就嘗試從MemoryCache中獲取數據。
4.然后調用Reqeust對應的ReqeustHandler去下載數據并解碼為Bitmap
5.通知統計線程更新統計信息
6.如果需要Transformation或者旋轉,那么則依次調用Transformation還有旋轉
7.根據結果result派發dispatcher.dispatchFailed(this);或者dispatcher.dispatchComplete(this);
dispatcher.dispatchComplete經過層層調用,最后是調用到picasso.complete()方法,如下
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();
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實現類是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));
}
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);
if (callback != null) {
callback.onSuccess();
}
}
到這里就完成了整個Picasso加載圖片的流程
說說其他需要注意的點
1.緩存策略
Picasso的緩存是內存緩存+磁盤緩存,內存緩存基于LruCache類,可以配置替換,磁盤緩存依賴于http緩存
內存緩存:
讀緩存
前面提到的流程其實也說到會從緩存找
RequestCreator#into
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;
}
}
寫緩存
在加載成功后,會有寫入緩存的流程,代碼如下
Dispatcher#performComplete
if (shouldWriteToMemoryCache(hunter.getMemoryPolicy())) {
cache.set(hunter.getKey(), hunter.getResult());
}
磁盤緩存:
如果你是使用UrlConnectionDownloader的話,那很不幸,緩存只在Api>14上生效,因為緩存依賴于HttpResponseCache.
如果你依賴了okhttp,那么緩存策略始終是有效的。另外需要說明的是,既然是http緩存,那么緩存的可用性依賴于http響應是
否允許緩存,也就是說得看響應中是否攜帶Cache-Control、Expires等字段.
2關于清理線程
在Picasso初始化時候我們提到了一個清理線程,這個線程主要作用是找到那些Target已經被回收,但是對應的Request請求孩子繼續的任務,找到后會取消對應的請求,避免資源浪費
private static class CleanupThread extends Thread {
private final ReferenceQueue<Object> referenceQueue;
private final Handler handler;
CleanupThread(ReferenceQueue<Object> referenceQueue, Handler handler) {
this.referenceQueue = referenceQueue;
this.handler = handler;
setDaemon(true);
setName(THREAD_PREFIX + "refQueue");
}
@Override public void run() {
Process.setThreadPriority(THREAD_PRIORITY_BACKGROUND);
while (true) {
try {
// Prior to Android 5.0, even when there is no local variable, the result from
// remove() & obtainMessage() is kept as a stack local variable.
// We're forcing this reference to be cleared and replaced by looping every second
// when there is nothing to do.
// This behavior has been tested and reproduced with heap dumps.
RequestWeakReference<?> remove =
(RequestWeakReference<?>) referenceQueue.remove(THREAD_LEAK_CLEANING_MS);
Message message = handler.obtainMessage();
if (remove != null) {
message.what = REQUEST_GCED;
message.obj = remove.action;
handler.sendMessage(message);
} else {
message.recycle();
}
} catch (InterruptedException e) {
break;
} catch (final Exception e) {
handler.post(new Runnable() {
@Override public void run() {
throw new RuntimeException(e);
}
});
break;
}
}
}
void shutdown() {
interrupt();
}
}
可以看到代碼不斷輪詢ReferenceQueue,找到這樣的reference,就交給handler,handler會從reference中拿到action,
并取消請求.
case REQUEST_GCED: {
Action action = (Action) msg.obj;
if (action.getPicasso().loggingEnabled) {
log(OWNER_MAIN, VERB_CANCELED, action.request.logId(), "target got garbage collected");
}
action.picasso.cancelExistingRequest(action.getTarget());
break;
}
3暫停與恢復請求
我們在開發過程中經常會使用到滑動不加載圖片,不滑動才加載圖片
pause:
Dispatcher#performPauseTag中遍歷所有的hunter,都會調一次cancel,我們看下BitmapHunter#cancel方法的代碼:
boolean cancel() {
return action == null
&& (actions == null || actions.isEmpty())
&& future != null
&& future.cancel(false);
}
注意到它會判斷action是否為空,如果不為空就不會取消了。而在Dispatcher#performPauseTag中會把tag匹配的
action與對應的BitmapHunter解綁(detach),讓BitmapHunter的action為空.所以這并不影響其他任務的執行。
resume
其實就是遍歷pausedActions,挨個重新交給dispatcher分發。