概述
在Android开发界,大家都知到square出品必属精品,图片加载库Picasso自然也是。本文就从源码角度,详细分析下Picasso。
基本使用
下面的代码为一次简单的网络加载图片
Picasso.with(getApplicationContext())
.load("http://www.qlnh.com/uploads/image/20160714/20160714114238_6824.jpg")
.placeholder(holderDrawable)
.error(errorDrawable)
.into(imageView);
可以看到,整个调用流程结构非常清晰,链式方法看起来也让人赏心悦目。当然这只是一个基本的网络加载图片例子,你也可以配置很多其他参数,如图片裁减,旋转等等。
下面详细分析Picasso
的核心类及加载流程
Picasso的初始化
Picasso库
采用了门面设计模式,调用都是从Picasso类
开始的,而Picasso
内部组件的初始化也是在Picasso类
中执行的。如果不需要自定义Picasso
,直接使用单例模式Picasso with(Context context)
获取Picasso
实例就可以了,而如果需要自定义Picasso
类则可以在调用Picasso with(Context context)
之前先通过setSingletonInstance(Picasso picasso)
来设置Picasso
。
下面来看看Picasso
有那些可以自定义的组件
public static class Builder {
private final Context context;
private Downloader downloader; //下载器
private ExecutorService service; //网络任务线程池
private Cache cache; //内存缓存
private Listener listener; //onImageLoadFailed 监听
private RequestTransformer transformer; //Request提交前的预留hook接口
private List<RequestHandler> requestHandlers; //请求处理者集合
private Bitmap.Config defaultBitmapConfig; //默认bitmap设置信息
private boolean indicatorsEnabled; //是否debug 信息提示显示
private boolean loggingEnabled; //是否打印log
...
如果没有自定义,Picasso
类就会使用默认配置。
public Picasso build() {
Context context = this.context;
if (downloader == null) {
downloader = Utils.createDefaultDownloader(context);
}
if (cache == null) {
cache = new LruCache(context);
}
if (service == null) {
service = new PicassoExecutorService();
}
if (transformer == null) {
transformer = RequestTransformer.IDENTITY;
}
Stats stats = new Stats(cache);
Dispatcher dispatcher = new Dispatcher(context, service, HANDLER, downloader, cache, stats);
return new Picasso(context, dispatcher, cache, listener, transformer, requestHandlers, stats,
defaultBitmapConfig, indicatorsEnabled, loggingEnabled);
}
下面来看看这些组件的默认配置:
- downloader
downloader 类是对网络实现的抽象接口,有Response load(Uri uri, int networkPolicy)
,void shutdown();
,InputStream getInputStream()
等方法。下面的创建默认实现的方法中会反射判断项目是否依赖okhttp
库,如果有okhttp
库就使用okhttp
来实现downloader
,否则就采用httpurlconnection
来实现。其实在volley
,glide
等开源库都有如此设计,可以方便切换okhttp
或者httpurlconnection
作为网络请求的默认实现。
static Downloader createDefaultDownloader(Context context) {
try {
Class.forName("com.squareup.okhttp.OkHttpClient");
return OkHttpLoaderCreator.create(context);
} catch (ClassNotFoundException ignored) {
}
return new UrlConnectionDownloader(context);
}
- cache
cache
接口作为内存缓存的抽象接口有以下方法
/** Retrieve an image for the specified {@code key} or {@code null}. */
Bitmap get(String key);
/** Store an image in the cache for the specified {@code key}. */
void set(String key, Bitmap bitmap);
/** Returns the current size of the cache in bytes. */
int size();
/** Returns the maximum size in bytes that the cache can hold. */
int maxSize();
/** Clears the cache. */
void clear();
/** Remove items whose key is prefixed with {@code keyPrefix}. */
void clearKeyUri(String keyPrefix);
默认的实现为LruCache
,既当内存达到最大值时移除最早的缓存
- service
默认实现为PicassoExecutorService
private static final int DEFAULT_THREAD_COUNT = 3;
PicassoExecutorService() {
super(DEFAULT_THREAD_COUNT, DEFAULT_THREAD_COUNT, 0, TimeUnit.MILLISECONDS,
new PriorityBlockingQueue<Runnable>(), new Utils.PicassoThreadFactory());
}
这个也好理解,就是一个线程数为3的固定线程池,注意这个线程池的的等待队列为PriorityBlockingQueue
。另一方面,Picasso
中注册了,接受了网络信号变化的广播接收者,当网络切换时会根据网络类型动态变化线程池的线程数。
- Dispatcher
Dispatcher
为Picasso
非常重要的一个类,所有任务的执行都要经它之手。其没有对使用者提供自定义选项。下面是一些dispatcher
的方法,基本都是将任务发送到其内部的一个handler
处理,这个handler
是运行的handlerthread
的专门来处理任务派发的。
...
void dispatchSubmit(Action action) {
handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));
}
void dispatchCancel(Action action) {
handler.sendMessage(handler.obtainMessage(REQUEST_CANCEL, action));
}
void dispatchResumeTag(Object tag) {
handler.sendMessage(handler.obtainMessage(TAG_RESUME, tag));
}
void dispatchComplete(BitmapHunter hunter) {
handler.sendMessage(handler.obtainMessage(HUNTER_COMPLETE, hunter));
}
void dispatchRetry(BitmapHunter hunter) {
handler.sendMessageDelayed(handler.obtainMessage(HUNTER_RETRY, hunter), RETRY_DELAY);
}
void dispatchFailed(BitmapHunter hunter) {
handler.sendMessage(handler.obtainMessage(HUNTER_DECODE_FAILED, hunter));
}
void dispatchNetworkStateChange(NetworkInfo info) {
handler.sendMessage(handler.obtainMessage(NETWORK_STATE_CHANGE, info));
}
...
- transformer &stats
这两个组件都是非核心组件,transformer 是给提交request前的一个hook接口,默认是直接返回request
RequestTransformer IDENTITY = new RequestTransformer() {
@Override public Request transformRequest(Request request) {
return request;
}
};
而stats 是负责统计的类,与核心功能无关。
核心类
下面以一次图片加载过程的顺序来介绍下这些核心类
Request&RequestCreator
Request
是封装图片请求(包括url,图片变形参数,请求优先级)等的model类,而RequestCreator
则是创建Request
的辅助类,其是非常重要的一个类。
我们通过Picasso.load()
方法会返回一个RequestCreator
对象,之后我们可以在RequestCreator
上设置placeholder
、error
等状态的图片,也可以设置transform
,rotate
等参数。最终通过into()
方法,创建request
并提交. into()
方法有好几种重载下面以target为imageview的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()) { //检查是否有设置url或者resId,若都没有抛出异常
picasso.cancelRequest(target);
if (setPlaceholder) {
setPlaceholder(target, getPlaceholderDrawable());
}
return;
}
if (deferred) {//fit()模式
if (data.hasSize()) { //fit()模式是适应target的宽高加载,不能手动设置resize,如果设置就抛出异常
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); //创建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) { //设置placeholder
setPlaceholder(target, getPlaceholderDrawable());
}
Action action = //创建Action
new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
errorDrawable, requestKey, tag, callback, noFade);
picasso.enqueueAndSubmit(action); //action入队
}
Action
Action
是封装了请求和target及内存策略等参数的类,在上一节的Requestcreator.into()
方法中创建,然后交由Picasso
类执行(picasso.enqueueAndSubmit(action)
),下面来看看这个提交过程都做了什么
//Picasso类中
void enqueueAndSubmit(Action action) {
Object target = action.getTarget();
if (target != null && targetToAction.get(target) != action) {//取消target此前的任务
// This will also check we are on the main thread.
cancelExistingRequest(target); //取消已存在的action
targetToAction.put(target, action); //添加到target-action map集合
}
submit(action);
}
void submit(Action action) {
dispatcher.dispatchSubmit(action); //委托dispatcher执行
}
//Dispatcher类中
void performSubmit(Action action) {
performSubmit(action, true);
}
void performSubmit(Action action, boolean dismissFailed) {
if (pausedTags.contains(action.getTag())) {
pausedActions.put(action.getTarget(), action); //如果需要pause则pause
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
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); //创建hunter
hunter.future = service.submit(hunter); //向线程池提交hunter
hunterMap.put(action.getKey(), hunter);
if (dismissFailed) {
failedActions.remove(action.getTarget());
}
if (action.getPicasso().loggingEnabled) {
log(OWNER_DISPATCHER, VERB_ENQUEUED, action.request.logId());
}
}
上面代码先是判断了target是否已存在action,如果是则pause之前的target,然后Picasso
类把任务的启动交给dispatcher
来执行,dispatcher
检查action对应的hunter
是否已创建,如果创建则直接将action
attachhunter
即可,如果hunter
没有创建则创建hunter
并将其提交给线程池执行.
BitmapHunter
由上一节可知一个请求任务最终的执行者就是bitmaphunter
,先来看看bitmaphunter
的创建:
static BitmapHunter forRequest(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats,
Action action) {
Request request = action.getRequest();
List<RequestHandler> requestHandlers = picasso.getRequestHandlers();
// Index-based loop to avoid allocating an iterator.
//noinspection ForLoopReplaceableByForEach
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);
}
BitmapHunter(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats, Action action,
RequestHandler requestHandler) {
this.sequence = SEQUENCE_GENERATOR.incrementAndGet();
this.picasso = picasso;
this.dispatcher = dispatcher;
this.cache = cache;
this.stats = stats;
this.action = action;
this.key = action.getKey();
this.data = action.getRequest();
this.priority = action.getPriority();
this.memoryPolicy = action.getMemoryPolicy();
this.networkPolicy = action.getNetworkPolicy();
this.requestHandler = requestHandler;
this.retryCount = requestHandler.getRetryCount();
}
bitmaphunter
对象的创建是有static 方法forRequest
完成的,其主要工作是根据request寻找到可以处理此request
的RequestHandler
,这里的寻找过程采用了责任链模式,可以借鉴一下.
Picasso
对象的requestHandlers
是在Picasso
初始化时创建的,其有以下几种
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)); //assert读取
allRequestHandlers.add(new FileRequestHandler(context)); //文件读取
allRequestHandlers.add(new NetworkRequestHandler(dispatcher.downloader, stats)); //网络获取
requestHandlers = Collections.unmodifiableList(allRequestHandlers);
通过责任链模式
我们可以很方便的扩展处理request的handler
再来看看bitmaphunter
类的run方法:
@Override public void run() {
try {
updateThreadName(data);
if (picasso.loggingEnabled) {
log(OWNER_HUNTER, VERB_EXECUTING, getLogIdsForHunter(this));
}
result = hunt(); //关键步骤,获取bitmap
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;
}
}
data.networkPolicy = retryCount == 0 ? NetworkPolicy.OFFLINE.index : networkPolicy;
RequestHandler.Result result = requestHandler.load(data, networkPolicy); //交由requestHandler获取图片
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);
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;
}
图片的获取就完成后,再交由dispatcher
去处理 dispatcher.dispatchComplete(this);
显示
在BitmapHunter
获取图片成功后,会交由dispatcher.dispatchComplete(this);
处理,最终会执行到以下
void performComplete(BitmapHunter hunter) {
if (shouldWriteToMemoryCache(hunter.getMemoryPolicy())) {
cache.set(hunter.getKey(), hunter.getResult()); //如果需要内存缓存则添加到cache中
}
hunterMap.remove(hunter.getKey());
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)) { //如果没有指定message则发送指定消息
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);
}
这里主要有一个batch处理让人费解, dispatcher
会以200ms
为一个周期区处理complete任务,至于为什么要有这个操作,个人猜测可能是基于性能考虑吧.
最终,dispatcher
会将200ms
内完成的任务发送到主线程(这个主线程handler定义在Picasso
类中),
主线程收到这个消息后会调用complete
方法,来看看这个方法:
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);
}
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(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());
}
}
}
最终,action.complete(result, from);
会被调用,在这个方法里面会对target设置bitmap(还有些加载动画等设置,此处不再赘述),至此图片加载完成。
总结
Picasso
获取图片资源并显示的代码流转过程如下:
-
Picasso.with()
获取Picasso实例 -
.load("url")
方法用传入的url创建一个RequestCreator
对象 -
.into(imageview)
方法创建此次request
并将其封装进action
再调用picasso.enqueueAndSubmit(action)
-
Picasso
类将action
对象交给dispatcher.submit()
-
dispatcher
类根据action
创建bitmapHunter
,并将bitmapHunter
提交至线程池执行
当bitmapHunter
获取到图片资源后,又经过了以下步骤最终显示在ImageView上
-
bitmapHunter
获取图片资源成功,调用dispatcher.dispatchComplete(this);
-
dispatcher
发送延迟200ms
、msg.what=HUNTER_DELAY_NEXT_BATCH
、携带200ms
内完成的bitmapHunter
封装为一个list的消息到主线程 - 主线程收到消息后,调用
Picasso
类的complete
方法,解析出bitmapHunter
中的action
-
action
的complete
方法内,将bitmap设置给Imageview
一次简单的图片加载虽然经历了这么多的步骤,但也换来了清晰的结构,强大的功能,良好的扩展性.而其中用到的设计模式也很值得学习.