Picasso源码分析

图片框架源码分析

Posted by Mio4kon on 2015-08-26

Picasso 简介

Picasso 是一个强大的图片下载缓存库,是Square公司的一个开源项目.

使用方法:

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

即实现了图片的下载缓存展示.

源码分析

Picasso.with(context)入口分析

1
2
3
4
5
6
7
8
9
10
11
public static Picasso with(Context context) {
if (singleton == null) {
synchronized (Picasso.class) {
if (singleton == null) {
singleton = new Builder(context).build();
}
}
}
return singleton;
}

利用builder模式创建Picasso实例.

Tips: 上述代码用到了双检测加锁机制.第一次检测避免排队浪费时间

创建实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//可见主要配置一些参数,如下载器,缓存方式,线程池,以及请求改变等.
/** 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); //缓存:使用LruCache,用了15%的内存空间作为缓存
}
if (service == null) {
service = new PicassoExecutorService(); //线程池:根据不同的网络情况,线程池的线程数量是不一样的(网络状况越差,线程数量越少)
}
if (transformer == null) {
transformer = RequestTransformer.IDENTITY; //这里返回原Request,如果在submitted之前可以通过Transformer修改Request
}
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);
}

下载器配置(其他默认配置可见源码)

1
2
3
4
5
6
7
8
9
//通过反射判断有没有OKhttpClient,如果有使用OkHttpClient,否则使用HttpURLConnection
static Downloader createDefaultDownloader(Context context) {
try {
Class.forName("com.squareup.okhttp.OkHttpClient");
return OkHttpLoaderCreator.create(context);
} catch (ClassNotFoundException ignored) {
}
return new UrlConnectionDownloader(context);
}

Picasso构造函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
Picasso(Context context, Dispatcher dispatcher, Cache cache, Listener listener,
RequestTransformer requestTransformer, List<RequestHandler> extraRequestHandlers, Stats stats,
Bitmap.Config defaultBitmapConfig, boolean indicatorsEnabled, boolean loggingEnabled) {
//.. 成员变量赋值
//内部默认有7个RequestHandler
int builtInHandlers = 7; // Adjust this as internal handlers are added or removed.
//可以定义额外的Handler,通过Builder.addRequestHandler
int extraCount = (extraRequestHandlers != null ? extraRequestHandlers.size() : 0);
List<RequestHandler> allRequestHandlers =
new ArrayList<RequestHandler>(builtInHandlers + extraCount);
// 下面对应内部的7个RequestHandler,以后会说的
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); //返回一个不可修改的list
this.stats = stats;
//.. 成员变量赋值
//弱引用Queue
this.referenceQueue = new ReferenceQueue<Object>();
this.cleanupThread = new CleanupThread(referenceQueue, HANDLER);
this.cleanupThread.start();
}

这里有一些细节,可以了解下,上述创建一个referenceQueue,用于存放以及被回收后的弱引用对应的Reference.
什么置为了弱引用呢?
Target,也就是into(ImageView)的ImageView.这个下面会看到.这里只需知道ImageView被置为弱引用.
而referenceQueue如果了解的话就知道其存储的是被回收后对象的Reference.
故而CleanupThread的作用就是清除这些Reference,并取消请求的.(比如我界面已经关闭了,imageview也被gc了,此时取消请求)

load方法

Picasso.java

1
2
3
public RequestCreator load(Uri uri) {
return new RequestCreator(this, uri, 0);
}

load方法创建了一个请求,我们来看看如何创建的

RequestCreator.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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);
}
@TestOnly RequestCreator() {
this.picasso = null;
this.data = new Request.Builder(null, 0, null);
}

发现又使用了builder模式创建了Requset(这里实际还没有创建Request对象,只是赋值给Builder,最终调into方法里会有一个createRequest方法这个时候才真正创建Request)

into(ImageView target) 方法

重头戏来了,前面都只是一些配置,正在执行下载缓存逻辑都是从此入口执行的.
into(ImageView target)会调用into(target, null)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
public void into(ImageView target, Callback callback) {
long started = System.nanoTime();
checkMain(); //不是主线程会报异常
if (target == null) {
throw new IllegalArgumentException("Target must not be null.");
}
//uri为空时取消请求,并设置展位图片
if (!data.hasImage()) {
picasso.cancelRequest(target);
if (setPlaceholder) {
setPlaceholder(target, getPlaceholderDrawable());
}
return;
}
//deferred为true表示是否适配控件大小(与resize不能同时存在)
//下面逻辑主要是修改Request中的target参数
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);
}
//这个之前说了创建Requset,其实就是调用Request.builder.build()
//如果之前设置了RequestTransformer,这里实际上会改Requset
Request request = createRequest(started);
String requestKey = createKey(request); //创建请求key
//从内存中获取缓存
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);
//将任务加入队列并提交
picasso.enqueueAndSubmit(action);
}

关于action,实际上是用于构建任务参数以及处理加载回调,里面有加载成功和失败的回调.
这里实例是ImageViewAction,因为我们是通过into(ImageView)这个方法进入的.所有处理的是ImageView相关任务.

ImageViewAction.class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//ImageViewAction相关回调实现
@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); //imageview设置bitmap
if (callback != null) {
callback.onSuccess();
}
}
@Override public void error() {
ImageView target = this.target.get();
if (target == null) {
return;
}
//加载失败,设置失败图片
if (errorResId != 0) {
target.setImageResource(errorResId);
} else if (errorDrawable != null) {
target.setImageDrawable(errorDrawable);
}
if (callback != null) {
callback.onError();
}
}
@Override void cancel() {
super.cancel();
if (callback != null) {
callback = null;
}
}

这里加载成功会通过PicassoDrawable.setBitmap(target, context, result, from, noFade, indicatorsEnabled); 设置Imageview的图片.
具体细节有兴趣可以阅读源码.大致是创建了PicassoDrawable主要是控制图片渐显的效果.

还记得之前说过的WeakReference吗?就是ImageView被置为弱引用.我们在Action.class这个抽象类就可以看到.

Action.class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
static class RequestWeakReference<M> extends WeakReference<M> {
final Action action;
public RequestWeakReference(Action action, M referent, ReferenceQueue<? super M> q) {
super(referent, q);
this.action = action;
}
}
Action(Picasso picasso, T target, Request request, int memoryPolicy, int networkPolicy,
int errorResId, Drawable errorDrawable, String key, Object tag, boolean noFade) {
//..
//这里target实际就是ImageView
this.target =
target == null ? null : new RequestWeakReference<T>(this, target, picasso.referenceQueue);
//..
}

Tips:为什么使用弱引用?
其实之前也提到了,如果界面关闭了,imageView就只剩弱引用了.被gc后,通过CleanupThread取消请求.减少资源开销.
关于WeakReference的应用,在Handler上也可以应用.具体可以了解下Handler造成的内存泄露.

回归正题,创建了Action之后自然是要运行,picasso.enqueueAndSubmit(action)就是运行的入口.

Picasso.class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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);
}

通过targetToAction这个Map集合避免了一个问题,同一个ImageView两次加载的问题.
这个在Listview中经常出现.ImageView被复用,但之前的加载请求没有完成.这里会取消之前未完成的任务.并添加新的任务.

分发器会将Action分发到Submit上去,跟到后面其实就是运行performSubmit(action, true);

Dispatcher.class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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()); //BitmapHunter就是一个Runnable
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;
}
//创建Runnable,并执行
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());
}
}

上面的代码关键在于BitmapHunter实际上是一个Runnable
通过forRequest(action.getPicasso(), this, cache, stats, action)创建了hunter并使用线程池执行runnable.
我们来看下BitmapHunter的run方法.

BitmapHunter.class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@Override public void run() {
try {
updateThreadName(data);
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 = hunt()执行了加载的逻辑.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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);
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;
}

这个方法很关键,开始先尝试从内存中读取图片,如果没有,会执行
requestHandler.load(data, networkPolicy),RequestHandler还记得吗?
之前在Picasso创建实例的时候默认创建了7个RequestHandler.对应不同的请求处理方式,有获取Asset图片的方式,获取文件资源的方式,获取网络资源的方式等等..

在通过forRequest创建BitmapHunter的时候实际上是会根据requestHandler.canHandleRequest(request)来返回对应的Hunter.如下

BitmapHunter.class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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);
//会通过canHandleRequest判断是否能处理这个请求.比如是网络请求就返回NetworkRequestHandler
if (requestHandler.canHandleRequest(request)) {
return new BitmapHunter(picasso, dispatcher, cache, stats, action, requestHandler);
}
}
return new BitmapHunter(picasso, dispatcher, cache, stats, action, ERRORING_HANDLER);
}

这里我们分析自然是网络获取图片的请求,也就是uri是一个网络连接,
通过上面分析,如果网络请求,requestHandler.load(data, networkPolicy)实际上调用的是NetworkRequestHandlerload方法.

NetworkRequestHandler.class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@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);
}

通过下载器获取响应数据,可能直接返回有Bitmap,可能是流数据,然后就是回到之前的方法了->hunt->run;
hunt方法后面做了:如果响应数据是流会转为Bitmap
run方法得到hunt方法返回的Bitmap数据并dispatcher.dispatchComplete(this);
这之后就是一系列Handler的处理.

Dispather.java

1
2
3
4
5
6
void performBatchComplete() {
List<BitmapHunter> copy = new ArrayList<BitmapHunter>(batch);
batch.clear();
mainThreadHandler.sendMessage(mainThreadHandler.obtainMessage(HUNTER_BATCH_COMPLETE, copy));
logBatch(copy);
}

可见最后是由mainThreadHandler处理,这个mainThreadHandler是从Dispatcher构造函数传来的,Dispatcher是什么时候构建的还记得吗?就是在构造Picasso的时候.

Picasso

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
Dispatcher dispatcher = new Dispatcher(context, service, HANDLER, downloader, cache, stats);
static final Handler HANDLER = new Handler(Looper.getMainLooper()) {
@Override public void handleMessage(Message msg) {
switch (msg.what) {
case HUNTER_BATCH_COMPLETE: {
@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
}
break;
}
//.....
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(); //得到bitmap
LoadedFrom from = hunter.getLoadedFrom();
if (single != null) {
deliverAction(result, from, single); //处理bitmap,根据不同Action处理(比如ImageViewAction就是设置imageView)
}
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);
}
}

到这里Picasso的源码大致分析完了.等等..好像只有内存缓存啊.文件缓存呢???
其实文件缓存封装到了Download(下载器)中了.之前提到通过反射如果有OkHttpClient就会使用OKHttp,否则使用HttpURLConnection.
这里我们只阅读下UrlConnectionDownloader的源码.

UrlConnectionDownloader.class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
@Override public Response load(Uri uri, int networkPolicy) throws IOException {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
installCacheIfNeeded(context); //设置file-cache,即../cache/picasso-cache
}
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);
}

以前在写文件缓存的时候,实际上逻辑是类似内存缓存写法,使用DiskLruCache,将uri进行md5转换唯一值作为文件名存储在本地.
而Picasso这里是利用了Http缓存机制本地缓存图片.
注意到上面判断了SDK>14才创建缓存文件.这是因为HttpResponseCache这个类是在android 4.0才引入的.