最近听闻现在用的较多的图片加载框架是picasso,查了下picasso和okhttp是属于同一个公司开发的,picasso在github现在的star量是13K+,看起来真的挺火的,因此决定对它的源码扒一扒。
研究源码之前首先的了解的它的使用方式,官网给的一个简单例子如下:
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
从Picass.with进入
public static Picasso with(Context context) {
if (singleton == null) {
synchronized (Picasso.class) {
if (singleton == null) {
singleton = new Builder(context).build();
}
}
}
return singleton;
}
发现picasso是一个懒加载单例模式;进入 Builder(context)方法
/** Start building a new {@link Picasso} instance. */
public Builder(Context context) {
if (context == null) {
throw new IllegalArgumentException("Context must not be null.");
}
this.context = context.getApplicationContext();
}
/** Create the {@link Picasso} instance. */
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);
}
}
至此,picasso的初始化就完成了。整个picasso单例引用了一个全局的ApplicationContext,当中初始化了以下几个重要的组件:
- downloader=UrlConnectionDownloader,负责网络请求。
- cache=LruCache,内存缓存(内部使用linkedHashMap),负责缓存bitmap
- service=PicassoExecutorService,一个线程池ExecutorService,负责以线程池的方式执行BitmapHunter
- transformer = RequestTransformer.IDENTITY,为改善图片加载速度使用,这儿要配置了cdn才有用
- dispatcher = new Dispatcher,负责调度图片加载action进入service
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));
}
public RequestCreator load(Uri uri) {
return new RequestCreator(this, uri, 0);
}
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);
}
通过一个uri构造一个RequestCreator,RequestCreator包含了一个对picasso和Request.Builder的引用。从Picasso和Request的初始化可以看到square公司对builder模式的喜爱。builder模式感觉可以叫设计模式中的建造者模式,builder模式的好处的是把对象的初始化交给builder类单独处理,自己只负责和业务相关的逻辑,这样避免了把很多的方法写到一个类中,提高了代码的可读性和已维护性。看过okhttp源码和retrofit源码的人应该知道,它们中的都大量的使用到了builder模式。
好了,此处稍微的跑偏了下,下面进入正题。RequestCreator创建好后,进入RequestCreator.into(ImageView target)
public void into(ImageView target) {
into(target, null);
}
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()) {
picasso.cancelRequest(target);
if (setPlaceholder) {
setPlaceholder(target, getPlaceholderDrawable());
}
return;
}
if (deferred) {
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 = createRequest(started);
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 =
new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
errorDrawable, requestKey, tag, callback, noFade);
picasso.enqueueAndSubmit(action);
}
此处代码较多,不过业务逻辑不难。checkMain()检测此处是否运行与主线程,然后检查target是否为空,是空的话直接抛出异常。一般情况下data.hasImage()等于true,deferred为false,因此这两步跳过。接着根据RequestCreator中的data创建出一个request,再以request创建一个与之对应的requestKey,然后根据requestKey去cache中寻找是否有与之对应的bitmap,这里是第一次加载,所以返回null。setPlaceholder默认是true,所以会首先会给target设置一个默认图片,设置完默认图片后,接着是把request以及一些相关的参数在做一层封装得到一个ImageViewAction。 下面是这两个类的成员图,缩进的表示类属性
ImageViewAction是对request的再次封装。得到一个ImageViewAction,picasso.enqueueAndSubmit(action),
void enqueueAndSubmit(Action action) {
Object target = action.getTarget();
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);
}
void submit(Action action) {
dispatcher.dispatchSubmit(action);
}
void dispatchSubmit(Action action) {
handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));
}
这段的作用其实就是让picasso里的dispatcher负责顺序调度对ImageViewAction作再一次的封装
@Override public void handleMessage(final Message msg) {
switch (msg.what) {
case REQUEST_SUBMIT: {
Action action = (Action) msg.obj;
dispatcher.performSubmit(action);
break;
}
void performSubmit(Action action) {
performSubmit(action, true);
}
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);
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());
}
}
由于Dispatcher里负责调度的是一个HandlerThread,也就是Dispatcher线程采用的是安卓特有的hanlder和looper轮询机制,提高了Thread的使用效率。
pausedTags里记录的是对暂停的ImageViewAction的引用,这里是第一次执行,pausedTags.contains(action.getTag())返回 false,hunterMap.get(action.getKey())也返回null,于是到了forRequest函数
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);
}
首先解释下RequestHandler的作用:由于图片来源的方式有多种,可以是资源Id、contendProvider、数据流、asset中的文件、本地文件以及网络等,而不同的来源相应的加载方式也就不一样,各种不同的RequestHandler就是解决从不同的地方加载图片的。PIcasso初始化的时候就内置了一些常用的requestHandler保存在requestHandlers集合中,如下
- ResourceRequestHandler
- ContactsPhotoRequestHandler
- MediaStoreRequestHandler
- ContentStreamRequestHandler
- AssetRequestHandler
- FileRequestHandler
- NetworkRequestHandler
class NetworkRequestHandler extends RequestHandler {
static final int RETRY_COUNT = 2;
private static final String SCHEME_HTTP = "http";
private static final String SCHEME_HTTPS = "https";
@Override public boolean canHandleRequest(Request data) {
String scheme = data.uri.getScheme();
return (SCHEME_HTTP.equals(scheme) || SCHEME_HTTPS.equals(scheme));
}
果真是NetworkRequestHandler ,在找到对应的RequestHandler之后,再对ImageViewAction做一层封装,就得到了一个BitmapHunter,
返回到上一层,由于bitmapHunter继承与runnable,因此可以交由service来执行,也就是图片加载的任务是由线程池执行。
其实到这里,图片加载都还未真正开始,从RequestCreator-->Request--> ImageViewAction -->BitmapHunter,前面的都是对一个图片加载任务的一层层封装,为的是前期收集
足够多的信息以便后面解析bitmap然后设置到ImageView。
在bitmapHunter被提交到service(ExecuteService)后,就等待线程池调度执行它的run方法了
@Override public void run() {
try {
updateThreadName(data);
if (picasso.loggingEnabled) {
log(OWNER_HUNTER, VERB_EXECUTING, getLogIdsForHunter(this));
}
result = hunt();
这一步没什么逻辑,直接看bitmapHunter的hunt方法
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);
这里再次检查cache中是否存在与key对应的bitmap缓存,这里假设第一次加载,返回null。然后就是requestHandler.load(data, networkPolicy),这里的requestHandler是NetworkRequestHandler
@Override public Result load(Request request, int networkPolicy) throws IOException {
Response response = downloader.load(request.uri, request.networkPolicy);
if (response == null) {
return null;
}
Picasso.LoadedFrom loadedFrom = response.cached ? DISK : NETWORK;
Bitmap bitmap = response.getBitmap();
if (bitmap != null) {
return new Result(bitmap, loadedFrom);
}
InputStream is = response.getInputStream();
if (is == null) {
return null;
}
// Sometimes response content length is zero when requests are being replayed. Haven't found
// root cause to this but retrying the request seems safe to do so.
if (loadedFrom == DISK && response.getContentLength() == 0) {
Utils.closeQuietly(is);
throw new ContentLengthException("Received response with 0 content-length header.");
}
if (loadedFrom == NETWORK && response.getContentLength() > 0) {
stats.dispatchDownloadFinished(response.getContentLength());
}
return new Result(is, loadedFrom);
}
NetworkRequestHandler 里接着又调用download.load方法,download是UrlConnectionDownloader
@Override public Response load(Uri uri, int networkPolicy) throws IOException {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
installCacheIfNeeded(context);
}
HttpURLConnection connection = openConnection(uri);
connection.setUseCaches(true);
if (networkPolicy != 0) {
String headerValue;
if (NetworkPolicy.isOfflineOnly(networkPolicy)) {
headerValue = FORCE_CACHE;
} else {
StringBuilder builder = CACHE_HEADER_BUILDER.get();
builder.setLength(0);
if (!NetworkPolicy.shouldReadFromDiskCache(networkPolicy)) {
builder.append("no-cache");
}
if (!NetworkPolicy.shouldWriteToDiskCache(networkPolicy)) {
if (builder.length() > 0) {
builder.append(',');
}
builder.append("no-store");
}
headerValue = builder.toString();
}
connection.setRequestProperty("Cache-Control", headerValue);
}
int responseCode = connection.getResponseCode();
if (responseCode >= 300) {
connection.disconnect();
throw new ResponseException(responseCode + " " + connection.getResponseMessage(),
networkPolicy, responseCode);
}
long contentLength = connection.getHeaderFieldInt("Content-Length", -1);
boolean fromCache = parseResponseSourceHeader(connection.getHeaderField(RESPONSE_SOURCE));
return new Response(connection.getInputStream(), fromCache, contentLength);
}
UrlConnectionDownloader首先判断系统版本,如果系统版本>=4.0就在内存中简历http缓存。然后就是根据uri打开一个HttpURLConnection,设置相应的请求头,然后从connection获取输入流,内容长度,最后封装成一个Response返回到上一层
Response返回到NetworkRequestHandler 的load方法。由于这里返回的Response的bitmap为null,因此在NetworkRequestHandler里又是把Response中的stream在封装成Result返回到上一层。
Result返回到BitmapHunter的hunt方法,这里再看hunt方法的下部分
data.networkPolicy = retryCount == 0 ? NetworkPolicy.OFFLINE.index : networkPolicy;
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);
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;
}
由于返回的result在请求成功的情况下不为空,但是result里的bitmap为null,因此会调用decodeStream(is, data)方法,该方法的作用是根据target的宽高来把is解析成bitmap,
后面bitmap还要request的要求做旋转、缩放、居中等操作,然后bitmap返回到上一层BitmapHunter的run方法,看run方法下部分
if (picasso.loggingEnabled) {
log(OWNER_HUNTER, VERB_EXECUTING, getLogIdsForHunter(this));
}
result = hunt();
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);
}
}
假设这里请求成功,result不为空,至此图片请求成功并且解析成了bitmap,接下来的事就是把bitmap设置到ImageView中了。由于安卓中操作UI需要在UI线程中执行,因此这里又用到了Dispatcher,由Dispatcher发送通知告知此BitmapHunter已经解析结束,然后把此BitmapHunter加到barch集合中,然后再通过主线程handler告知主线程执行最后的ImageView设置bitmap工作,也就是最后调用ImageViewAction的complete方法
class ImageViewAction extends Action<ImageView> {
@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.setBitmap(target, context, result, from, noFade, indicatorsEnabled);
if (callback != null) {
callback.onSuccess();
}
}
至此,bitmap就显示到ImageView上了,也就是图片加载成功了。
ok,最后我们来理一下picasso几个重要的组件类关系图
总结:
Picasso默认简单的请求加载下是不会对大图缩放的,即加载大图的话消耗的内存很多,所以如果在加载很多大图的情况下建议要主动resize已防止oom,如下
Picasso.with(this).load("uri").resize(50,50).centerCrop().config(Bitmap.Config.ARGB_8888).into(view)。
Picasso使用线程池执行网络请求,1个线程负责调度,主线程Handler负责调度每隔200毫秒一次显示view。它的requestHandler采用有点类似适配器的方式,使开发者可以实现自己的requestHandler,picasso各组件职责单一,使代码耦合度低,具有高可扩展性,很值得学习。