Picasso源码解析
Posted TonyW92
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Picasso源码解析相关的知识,希望对你有一定的参考价值。
前言
Picasso和OKHttp同属大名鼎鼎的Square公司,是一款优秀的图片处理框架。而一款图片处理框架无外乎流的加载,内存和硬盘缓存等内容,学习这些优秀的图片框架,可以增强我们对这方面的理解。
使用方法
//Picasso支持File,path,Uri,resourceId 4种加载图片
//最简单的显示方式
imageView = (ImageView) findViewById(R.id.img);
Picasso.with(this).load("https://www.baidu.com/img/bd_logo1.png").into(imageView);
//还可以预加载
//预加载一张图片
Picasso.with(this).load("https://www.baidu.com/img/bd_logo1.png").fetch();
效果图
关系图
这是来自Skykai
的关系类图,很详尽的展示了Picasso的类之间的关系
但是往往太详尽的东西都不太好理解,所以贴一张我整理的流程图,便于大家理解
源码分析
我们来看看
Picasso.with(this).load("https://www.baidu.com/img/bd_logo1.png").into(imageView);
这句简单的代码是如何把一张远程图片显示到ImageView上的
首先来看看Picasso.with(this)干了些什么
public static Picasso with()
if (singleton == null)
synchronized (Picasso.class)
if (singleton == null)
if (PicassoProvider.context == null)
throw new IllegalStateException("context == null");
singleton = new Builder(PicassoProvider.context).build();
return singleton;
显然Picasso是一个单例模式,向外提供服务,同时通过构造器的模式产生实例。
public Picasso build()
Context context = this.context;
if (downloader == null)
downloader = new OkHttp3Downloader(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的下载器是使用OkHttp3Downloader,毕竟是自己家的产品。缓存是使用LRU,内部也就是维护了一个LinkedHashMap,线程池是自己写的一个PicassoExecutorService。使用构建器可以很灵活的替换掉这几部分,体现了组件化开发的优势。
再来看下Picasso的构造函数干了些什么
Picasso(Context context, Dispatcher dispatcher, Cache cache, Listener listener,
RequestTransformer requestTransformer, List<RequestHandler> extraRequestHandlers, Stats stats,
Bitmap.Config defaultBitmapConfig, boolean indicatorsEnabled, boolean loggingEnabled)
this.context = context;
this.dispatcher = dispatcher;
this.cache = cache;
this.listener = listener;
this.requestTransformer = requestTransformer;
this.defaultBitmapConfig = defaultBitmapConfig;
int builtInHandlers = 7; // Adjust this as internal handlers are added or removed.
int extraCount = (extraRequestHandlers != null ? extraRequestHandlers.size() : 0);
List<RequestHandler> allRequestHandlers = new ArrayList<>(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);
this.stats = stats;
this.targetToAction = new WeakHashMap<>();
this.targetToDeferredRequestCreator = new WeakHashMap<>();
this.indicatorsEnabled = indicatorsEnabled;
this.loggingEnabled = loggingEnabled;
this.referenceQueue = new ReferenceQueue<>();
this.cleanupThread = new CleanupThread(referenceQueue, HANDLER);
this.cleanupThread.start();
可以看到主要是将构造器的参数赋值给自己,然后还干了一件很重要的事,保存了几个RequestHandler的实例,用于处理不同类的图片请求,并且采用了责任链的设计模式去处理。
接着看看load("https://www.baidu.com/img/bd_logo1.png")
做了些什么
public RequestCreator load(@Nullable Uri uri)
return new RequestCreator(this, uri, 0);
public RequestCreator load(@Nullable 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));
就简单的产生了一个RequestCreator对象
看来主要的逻辑都在into(imageView)里了
public void into(ImageView target, Callback callback)
//首先记录下请求时间
long started = System.nanoTime();
//然后确认了下是不是在主线程
checkMain();
if (target == null)
throw new IllegalArgumentException("Target must not be null.");
//对image的url合法性进行校验
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 || target.isLayoutRequested())
if (setPlaceholder)
setPlaceholder(target, getPlaceholderDrawable());
picasso.defer(target, new DeferredRequestCreator(this, target, callback));
return;
data.resize(width, height);
//这里就是真正的请求开始
//主要记录了请求的时间,id和一些裁剪和缓存的策略
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 action =
new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
errorDrawable, requestKey, tag, callback, noFade);
//这里重新回到picasso
picasso.enqueueAndSubmit(action);
可以看到RequestCreator主要起到验证缓存,组装请信息的作用
然后回到Picasso看看
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);
这里也非常简单检验了下target的合法性,一般tag都是context然后就交给dispatcher了
void dispatchSubmit(Action action)
handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));
'''省略一大段代码'''
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;
//得到hunter对象,对于第一次请求的,hunter都为null,这里主要为失败后重新请求服务
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;
//通过forRequest得到hunter对象,hunter本身是一个Runnable,所以可以通过线程池的submit执行
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只是起到了分发的作用,和它的名字和符合。真正的业务处理应该在hunter中。
首先是如何产生BitmapHunter这个对象
static BitmapHunter forRequest(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats,
Action action)
Request request = action.getRequest();
//这里的requestHandlers 就是Picasso的构造函数中生成的那些,根据条件来挑选可以执行当前请求的handler
//对于网络请求,采用的应该是NetworkRequestHandler
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);
然后看看hunter的run方法
@Override public void run()
try
//首先更新ThreadLocal中该线程对应的名字
updateThreadName(data);
if (picasso.loggingEnabled)
log(OWNER_HUNTER, VERB_EXECUTING, getLogIdsForHunter(this));
//通过hunt()这个方法得到Bitmap
result = hunt();
//如果result不为空,就执行complete方法,否则调用dispatchFailed
if (result == null)
dispatcher.dispatchFailed(this);
else
dispatcher.dispatchComplete(this);
//各种异常对应的处理方法
catch (NetworkRequestHandler.ResponseException e)
if (!NetworkPolicy.isOfflineOnly(e.networkPolicy) || e.code != 504)
exception = e;
dispatcher.dispatchFailed(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 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.OFFLINE.index : networkPolicy;
//使用requestHandler执行网络请求,得到结果
RequestHandler.Result result = requestHandler.load(data, networkPolicy);
if (result != null)
loadedFrom = result.getLoadedFrom();
exifOrientation = result.getExifOrientation();
bitmap = result.getBitmap();
//首先看下得到的Bitmap是否为空,如果为空就需要对流进行decode
// If there was no Bitmap then we need to decode it from the stream.
if (bitmap == null)
Source source = result.getSource();
try
//通过流得到bitmap
bitmap = decodeStream(source, data);
finally
try
//noinspection ConstantConditions If bitmap is null then source is guranteed non-null.
source.close();
catch (IOException ignored)
//根据预设规则对bitmap进行裁剪
if (bitmap != null)
if (picasso.loggingEnabled)
log(OWNER_HUNTER, VERB_DECODED, data.logId());
stats.dispatchBitmapDecoded(bitmap);
if (data.needsTransformation() || exifOrientation != 0)
synchronized (DECODE_LOCK)
if (data.needsMatrixTransform() || exifOrientation != 0)
bitmap = transformResult(data, bitmap, exifOrientation);
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;
这里可以得出结论hunt()这个方法还是不涉及到网络请求,只是根据结果对流进行处理,有兴趣的同学可以自行看下decodeStream这个方法
我们只能接着看下NetworkRequestHandler里的load方法了
@Override public Result load(Request request, int networkPolicy) throws IOException
//看到这,终于找到了网络请求的处理了
//在Picasso的Bulid中我们看到downloader默认是OkHttp3Downloader
//所以这里使用OkHttp3Downloader进行请求和硬盘的缓存
//缓存的地址是/data/data/package name/cache/picasso-cache
//之后的文章中可以详细讨论下OKHttp的请求实现,这里我们得到一个结论即可
okhttp3.Request downloaderRequest = createRequest(request, networkPolicy);
Response response = downloader.load(downloaderRequest);
ResponseBody body = response.body();
if (!response.isSuccessful())
body.close();
throw new ResponseException(response.code(), request.networkPolicy);
// Cache response is only null when the response comes fully from the network. Both completely
// cached and conditionally cached responses will have a non-null cache response.
Picasso.LoadedFrom loadedFrom = response.cacheResponse() == null ? NETWORK : DISK;
// 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 && body.contentLength() == 0)
body.close();
throw new ContentLengthException("Received response with 0 content-length header.");
if (loadedFrom == NETWORK && body.contentLength() > 0)
stats.dispatchDownloadFinished(body.contentLength());
return new Result(body.source(), loadedFrom);
再得到bitmap后,我们最后看下dispatcher的performComplete方法
void performComplete(BitmapHunter hunter)
//这里根据缓存策略,决定是否存储到内存,也就是LRU对应的map
if (shouldWriteToMemoryCache(hunter.getMemoryPolicy()))
cache.set(hunter.getKey(), hunter.getResult());
//清除这个请求对应的hunter
hunterMap.remove(hunter.getKey());
batch(hunter);
if (hunter.getPicasso().loggingEnabled)
log(OWNER_DISPATCHER, VERB_BATCHED, getLogIdsForHunter(hunter), "for completion");
总结
结合流程图,我们可以清楚的了解到Picasso的网络请求(OKHttp),内存缓存(LRU)和硬盘缓存(OKHttp代为执行)
也可以通过源代码发现Picasso默认是不会把硬盘上的缓存加载进来,因为LRUcache在初始化的时候是new出来的。我们需要通过Build构建一个我们自己的Picasso对象,然后执行setSingletonInstance方法,设置我们自己的单例。
Cache cache = DO SOMETHING//把硬盘里的缓存加载进来
Picasso picasso = new Picasso.Builder(this).memoryCache(cache ).build();
Picasso.setSingletonInstance(picasso);
从Picasso中我们总结出灵活这个词,每个模块都可以被调用方定制,替换。Picasso只制定流程,不关心细节,这点我们在设计流程的时候可以大大参考一下!
以上是关于Picasso源码解析的主要内容,如果未能解决你的问题,请参考以下文章