Picasso 是一款老牌的图片加载器,特别小巧,功能上虽然比不上 Glide 和 Fresco。可是通常的图片加载需求都能知足。关键是 square 出品,JakeWharton 大神主导的项目,必属精品,和自家的 OkHtttp 无缝衔接。html
分析版本: 2.5.2java
Picasso.with(this)
.load("https://www.kaochong.com/static/imgs/ic_course_logo_92e76ec.png")
.into(imageView);
复制代码
看了几个开源库,都是一个套路,先用门面模式提供一个单例给外部访问,这里是 Picasso,其余开源框架如 EventBus,Retrofit 都是同样的。由于开源须要知足不少 feature 避免不了使用一堆参数,建造者模式也是很常见的,几乎每一个开源库必备。数组
public static Picasso with(Context context) {
if (singleton == null) {
synchronized (Picasso.class) {
if (singleton == null) {
singleton = new Builder(context).build();
}
}
}
return singleton;
}
复制代码
接着看 load 方法:缓存
load 有 4 个重载方法:bash
load(Uri)
load(String)
load(File)
load(int)
分别对应加载不一样的来源。 这个方法会构造一个 RequestCreator
对象并返回。这个 RequestCreator
看名字就知道,是负责建立图片请求的。RequestCreator
和 Request
的区别在于,Request
是最终建立完成的请求,全部关于图片的信息都在这个请求里,包括图片大小,图片怎么转换,图片是否有渐变更画等等。而 RequestCreator
是一个 Request
的生产者,负责把请求参数组合而后建立成一个 Request
。网络
Picasso.with(this).load("url").placeholder()
.resize()
.transform()
.error()
.noFade()
.networkPolicy()
.centerCrop()
.into(imageview);
复制代码
上面这段代码中,load()
返回的是 RequestCreator
对象,后面从 placeholder()
到 into()
都是 RequestCreator
的中的方法。直到在 into()
中才会把最终图片请求 Request
对象构造出来处理。因此以前都是一堆参数的设置。app
以 load(String)
为例看看内部的操做:框架
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));
}
复制代码
load(String)
其实调用的是 load(Uri)
:ide
public RequestCreator load(Uri uri) {
return new RequestCreator(this, uri, 0);
}
复制代码
RequestCreator 的构造中,传入了 picasso 实例,用传入的 Uri、resourceId、默认 Bitmap 参数在内部构造一个 Request.Builder 实例,用于拼接后续参数最终 build 出一个 Request 实例。oop
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);
}
复制代码
后面的 error()
、placeholder()
等等就很简单了,就是把参数进行赋值修改。
关键的地方来了。 into 有 4 个重载方法:
into(Target)
into(RemoteViews,int,int,Notification)
into(RemoteViews,int,int[])
into(ImageView)
into(ImageView,Callback)
第 1 个用于实现了 Target 接口的对象,第 二、3 用于 RemoteView 的加载,分别用于通知和桌面小部件。4 和 5 就是咱们经常使用的方法,把图片加载到 ImageView, 区别是 5 有回调。这 5 个流程基本是同样,咱们就看 5 来看看加载的具体过程。
public void into(ImageView target, Callback callback) {
// 获取加载的开始时间,纳秒级别的,由于加载很快的
long started = System.nanoTime();
// 检查是否在主线程
checkMain();
// target 不能为空,否则无法加载
if (target == null) {
throw new IllegalArgumentException("Target must not be null.");
}
// 没图片就设置占位图
if (!data.hasImage()) {
picasso.cancelRequest(target);
if (setPlaceholder) {
setPlaceholder(target, getPlaceholderDrawable());
}
return;
}
// 若是是 fit 模式,图片自适应控件的大小,须要等 View layout 完肯定宽和高再加载。这里采用的是监听 OnPreDraw 接口的方法。
if (deferred) {
// fit 模式不能指定图片大小,和 resize 冲突
if (data.hasSize()) {
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 request = createRequest(started);
// 建立 Request key 用于缓存 Request
String requestKey = createKey(request);
// 首先从内存中查找,内存中有就把这个请求取消,直接从内存加载
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;
}
}
// 设置占位图
if (setPlaceholder) {
setPlaceholder(target, getPlaceholderDrawable());
}
// 构造出 Action
Action action =
new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
errorDrawable, requestKey, tag, callback, noFade);
// 将 Action 入队执行
picasso.enqueueAndSubmit(action);
}
复制代码
into 中会检查调用代码是否在主线程,由于要更新 View,还有回调,确定要在主线程。而后判断是否有图片的源地址,若是给的是个 null,那么直接就终止请求了。若是设置了 fit 模式(自适应 ImageView 的宽和高),fit 模式和 resize 冲突,既然自适应宽高了,确定就不能指定宽高。自适应 ImageView 的宽和高须要等待测量完成后获得宽高再继续请求,不然获得的宽高是 0,Picasso 使用 ViewTreeObserver 监听 ImageView 的 OnPreDrawListener 接口来获取宽和高,详细的代码能够看 DeferredRequestCreator
这个类。
而后建立出最终的 Request,此时的 Request 就表明了最终的图片请求信息。而后没有直接去请求,而是去缓存中查找,有的话就直接取消请求从内存中加载。没有的话就建立一个 ImageViewAction
, 它是 Action
的子类。加载到不一样的 Target 会使用不一样的 Action。加载到 Target
使用 TargetAction
。加载到通知就使用 NotificationAction
。能够去其余的 into
方法中查看源码。
Action
是一个抽象类, 内部封装了图片的请求信息,以及当前图片请求的其余参数(缓存策略,网络策略,是否取消了请求,Tag, 是否有动画等等)。须要子类实现 2 个方法:
// 解析图片完成后拿到 Bitmap,子类定义如何显示
abstract void complete(Bitmap result, VanGogh.LoadedFrom from);
// 解析发送错误
abstract void error(Exception e);
复制代码
这下能够理解它为啥叫 Action
了,它须要子类本身处理 Bitmap。定义本身的 Action (行为), 成功拿到 Bitmap 怎么办,发生错误了怎么办?
ImageViewAction 的实现很简单,内部经过自定义 BitmapDrawable 来绘制本身的图像,实现渐变。加载错误的时候就放置占位图。
接着看这最后一行 picasso.enqueueAndSubmit(action);
看看把 action
扔到哪去处理了。
void enqueueAndSubmit(Action action) {
Object target = action.getTarget();
if (target != null && targetToAction.get(target) != action) {
// 取消原来 target 的 action,将新的 action 存入
cancelExistingRequest(target);
targetToAction.put(target, action);
}
submit(action);
}
void submit(Action action) {
dispatcher.dispatchSubmit(action);
}
void dispatchSubmit(Action action) {
handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));
}
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;
}
// 将 action 合并,action 的 key 是根据 Request 中图片参数生成的,
// 这里的意思就是若是图片请求彻底同样,只是 Action 不同,只须要请求一次拿到 Bitmap 就行,
// 由于图片信息彻底相同,一个 Request 对应了对个 Action
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
hunter = forRequest(action.getPicasso(), this, cache, stats, action);
// 扔给线程池执行并得到结果
hunter.future = service.submit(hunter);
// 缓存 hunter
hunterMap.put(action.getKey(), hunter);
// 是否移除请求失败的 Action
if (dismissFailed) {
failedActions.remove(action.getTarget());
}
}
复制代码
跟踪能够发现交给 Dispatcher 中的 handler 处理了。
在 performSubmit()
中重点看 forRequest()
方法构造出 BitmapHunter 实例。
static BitmapHunter forRequest(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats, Action action) {
Request request = action.getRequest();
List<RequestHandler> requestHandlers = picasso.getRequestHandlers();
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);
}
复制代码
forRequest()
中遍历全部的 RequestHandler。谁能处理 Action 就处理这个 Action。这是典型的责任链模式- 《JAVA与模式》之责任链模式。
在 Picasso 实例初始化的时候就把这些 RequestHandler 都加入了列表中。
Picasso(Context context, Dispatcher dispatcher, Cache cache, Listener listener,
RequestTransformer requestTransformer, List<RequestHandler> extraRequestHandlers...) {
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);
}
复制代码
每一个 RequestHandler 重写 canHandleRequest
来代表本身能处理哪一种请求。
BitmapHunter 是一个 Runnable
, 构造以后交给线程池处理。来看看 BitmapHunter 的 run()
。
@Override public void run() {
try {
updateThreadName(data);
// 解析图片获得 Bitmap
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);
}
}
复制代码
首先由 hunt()
方法解析出 Bitmap,再把解析后的结果交给 Dispatcher 来分发,成功了咋样,失败了咋样,失败了是否重试。Dispatcher 在 Picasso 中扮演了重要的角色,负责整个流程的调度。
看看 hunt() 是怎么解析出 Bitmap 的。首先仍是从内存中取,每一个 RequestHandler 对象都持有了下载器,用于下载网络图片。网络图片下载完是一个流须要解析成 Bitmap,非网络的就直接获得一个 Bitmap。最后在处理变换操做获得最终的 bitmap。
Bitmap hunt() throws IOException {
Bitmap bitmap = null;
// 从内存缓存中取
if (shouldReadFromMemoryCache(memoryPolicy)) {
bitmap = cache.get(key);
if (bitmap != null) {
// 统计 缓存命中
stats.dispatchCacheHit();
loadedFrom = MEMORY;
return bitmap;
}
}
data.networkPolicy = retryCount == 0 ? NetworkPolicy.OFFLINE.index : networkPolicy;
// 用下载器请求url获得结果
RequestHandler.Result result = requestHandler.load(data, networkPolicy);
if (result != null) {
loadedFrom = result.getLoadedFrom();
exifRotation = result.getExifOrientation();
bitmap = result.getBitmap();
// 从流中解析出 Bitmap
if (bitmap == null) {
InputStream is = result.getStream();
try {
bitmap = decodeStream(is, data);
} finally {
Utils.closeQuietly(is);
}
}
}
if (bitmap != null) {
// 解码
stats.dispatchBitmapDecoded(bitmap);
if (data.needsTransformation() || exifRotation != 0) {
// 同一时间只处理一个 bitmap
synchronized (DECODE_LOCK) {
if (data.needsMatrixTransform() || exifRotation != 0) {
bitmap = transformResult(data, bitmap, exifRotation);
}
if (data.hasCustomTransformations()) {
bitmap = applyCustomTransformations(data.transformations, bitmap);
}
}
}
}
return bitmap;
}
复制代码
Dispatcher 内部实例化了一个 HandlerThread,全部的调度都是经过这个子线程上执行,经过这个子线程的 Handler 和 主线程的 Handler 以及线程池互相通讯。
解析图片的获得 Bitmap 后,Dispatcher 会调度到 dispatchComplete
,跟踪代码走到 performComplete
。
void performComplete(BitmapHunter hunter) {
// 是否写入内存缓存
if (shouldWriteToMemoryCache(hunter.getMemoryPolicy())) {
cache.set(hunter.getKey(), hunter.getResult());
}
hunterMap.remove(hunter.getKey());
// 批处理 hunter
batch(hunter);
}
// 执行批处理
void performBatchComplete() {
List<BitmapHunter> copy = new ArrayList<BitmapHunter>(batch);
batch.clear();
mainThreadHandler.sendMessage(mainThreadHandler.obtainMessage(HUNTER_BATCH_COMPLETE, copy));
logBatch(copy);
}
复制代码
最终将一批 BitmapHunter 打包一块儿扔给主线程处理。跟踪代码到 Picasso
类中的主线程的 Handler, 遍历执行 complete(hunter)
@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);
}
复制代码
complete(hunter)
中将调用 Action
的 complete
/error
方法进行最后一步把 Bitmap 显示到 target 上,并进行相应的成功或者失败回调。
引用一下blog.happyhls.me的图(本身懒得画了%>_<%),上面的流程能够总结成:
看源码的过程当中发现 Dispatcher 里面一堆 handler send message,和 ActivityThread 中 H 和 AMS 通讯很像,都用 Handler 来进行通讯。Handler 真是 Android 的精髓。