Picasso源码分析(一):单例模式、建造者模式、面向接口编程
Picasso源码分析(二):默认的下载器、缓存、线程池和转换器
Picasso源码分析(三):快照功能实现和HandlerThread的使用
Picasso源码分析(四):不变模式、建造者模式和Request的预处理
Picasso源码分析(五):into方法追本溯源和责任链模式创建BitmapHunter
Picasso源码分析(六):BitmapHunter与请求结果的处理
into方法流程回顾
into方法首先检查了是否在主线程,控件是否为null,用户有没有设置uri或者资源id,是否调用了fit方法自适应压缩。接着根据into方法调用时间创建Request请求,并为该请求设置缓存用的key。接着判断是否要读内存缓存,可以读内存缓存并且命中的话就将缓存中的图片显示在控件然后返回,否则开启网络请求。网络请求的过程中暂时显示占位图。
网络请求的过程就是针对此次请求封装成一个ImageViewAction的请求动作,通过Picasso将此动作递交给调度器dispatcher,在dispatcher中进行线程切换,在工作线程中处理该动作。处理的方法就是为这个动作创建一个BitmapHunter(实现了Runnable接口),然后把这个BitmapHunter交给线程池去处理。
BitmapHunter分析
BitmapHunter作为一个Runnable,是要交付给线程池执行的,所以重点关注实现的run方法。
@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()