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分发。