说说关于Picasso的源码分析

Picasso.with(this).load("").placeholder(R.mipmap.ic_launcher).into(imageView);

这是一个Picasso的使用方式,从这里入手来看看Picasso的源码构造方式

首先看一下Picasso.with()方法,如下

  public static Picasso with(Context context) {
    if (singleton == null) {
      synchronized (Picasso.class) {
        if (singleton == null) {
          singleton = new Builder(context).build();
        }
      }
    }
    return singleton;
  }

这里使用了单例模式,创建了全局唯一的Picasso实例

   public Picasso build() {
      Context context = this.context;
        
      if (downloader == null) {
        //默认下载器
        downloader = Utils.createDefaultDownloader(context);
      }
      if (cache == null) {
        //lru内存缓存
        cache = new LruCache(context);
      }
      if (service == null) {
        //创建线程池,默认3个执行线程
        service = new PicassoExecutorService();
      }
      if (transformer == null) {
       //创建默认的transformer,并无实际作用
        transformer = RequestTransformer.IDENTITY;
      }
      //创建默认的监控器(Stats),用于统计缓存命中率、下载时长等等
      Stats stats = new Stats(cache);
     //创建dispatcher对象用于任务的调度
      Dispatcher dispatcher = new Dispatcher(context, service, HANDLER, downloader, cache, stats);

      return new Picasso(context, dispatcher, cache, listener, transformer, requestHandlers, stats,
          defaultBitmapConfig, indicatorsEnabled, loggingEnabled);
    }
  }

最后一个方法创建了Picasso的实例对象

这里面主要做关于一些赋值操作,以及创建一些新的对象,例如清理线程等等.最重要的是初始化了requestHandlers,如下

 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));
    allRequestHandlers.add(new FileRequestHandler(context));
    allRequestHandlers.add(new NetworkRequestHandler(dispatcher.downloader, stats));
    requestHandlers = Collections.unmodifiableList(allRequestHandlers);

接下来就是调用load()方法传入String,Uri或者File对象了

这里的load()方法均是创建了RequestCreator对象,如下

 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);
  }

而into()方法则是RequestCreator方法如下

  public void into(ImageView target, Callback callback) {
    long started = System.nanoTime();
    //检查调用是否在主线程
    checkMain();

    if (target == null) {
      throw new IllegalArgumentException("Target must not be null.");
    }

    //如果没有设置需要加载的uri,或者resourceId
    if (!data.hasImage()) {
      picasso.cancelRequest(target);
      if (setPlaceholder) {
        setPlaceholder(target, getPlaceholderDrawable());
      }
      return;
    }

    //如果是延时加载,也就是选择了fit()模式
    if (deferred) {
      //fit()模式是适应target的宽高加载,所以并不能手动设置resize,如果设置就抛出异常
      if (data.hasSize()) {
        throw new IllegalStateException("Fit cannot be used with resize.");
      }
      int width = target.getWidth();
      int height = target.getHeight();
      //如果目标ImageView的宽或高现在为0
      if (width == 0 || height == 0) {
        //先设置占位符
        if (setPlaceholder) {
          setPlaceholder(target, getPlaceholderDrawable());
        }
        //监听ImageView的ViewTreeObserver.OnPreDrawListener接口,一旦ImageView
        //的宽高被赋值,就按照ImageView的宽高继续加载.
        picasso.defer(target, new DeferredRequestCreator(this, target, callback));
        return;
      }
      //如果ImageView有宽高就设置设置
      data.resize(width, height);
    }

    //构建Request
    Request request = createRequest(started);
    //构建requestKey
    String requestKey = createKey(request);

    //根据memoryPolicy来决定是否可以从内存里读取
    if (shouldReadFromMemoryCache(memoryPolicy)) {
      //通过LruCache来读取内存里的缓存图片
      Bitmap bitmap = picasso.quickMemoryCacheCheck(requestKey);
      if (bitmap != null) {
        //取消target的request
        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对象,由于我们是往ImageView里加载图片,所以这里创建的是一个ImageViewAction对象.
    Action action =
        new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
            errorDrawable, requestKey, tag, callback, noFade);
    //将Action对象入列提交
    picasso.enqueueAndSubmit(action);
  }

步骤如下:

1.检查是否工作在主线程,如果不在则直接抛出异常退出

2.如果没有Uri或者resoure Id,则取消该请求,并设置默认显示图片并退出

3.是否需要延迟执行,需要,则判断是否设置过targetSize,如果已经设置过,则抛出异常退出,没有设置过,则获取target,即ImageView对应的长和宽,如果长和宽都是0,那么就设置默认的图片,并构建一个DeferredRequestCreator,放入Picasso对应的队列当中

4.创建Reqeust,生成requestKey

5.判断是否需要跳过MemoryCache,如果不跳过,那么就尝试获取图片,并取消对应的请求,进行回调。

6.没有从缓存中获取到,则据是否设置了占位图并设置占位

7.生成对应的ImageViewAction,并将其添加到队列中

接下来就是任务相关的调度了,通过代码可以看到添加队列后,经过调用调到Dispatcher的performSubmit方法如下

void performSubmit(Action action, boolean dismissFailed) {
    //是否是需要被暂停的tag
    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;
    }

    //通过action的key来在hunterMap查找是否有相同的hunter
    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;
    }

    //创建BitmapHunter对象
    hunter = forRequest(action.getPicasso(), this, cache, stats, action);
    //通过service执行hunter并返回一个future对象
    hunter.future = service.submit(hunter);
    //将hunter添加到hunterMap中
    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接口,所以run()方法就会被执行,所以我们继续看看BitmapHunter里run()方法的实现,如下:

@Override public void run() {
    try {
      //更新当前线程的名字
      updateThreadName(data);

      if (picasso.loggingEnabled) {
        log(OWNER_HUNTER, VERB_EXECUTING, getLogIdsForHunter(this));
      }

      //调用hunt()方法并返回Bitmap类型的result对象
      result = hunt();

      //调用dispatcher发送相关消息
      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;
      }
    }

    //如果未设置networkPolicy并且retryCount为0,则将networkPolicy设置为NetworkPolicy.OFFLINE
    data.networkPolicy = retryCount == 0 ? NetworkPolicy.OFFLINE.index : networkPolicy;
    //通过对应的requestHandler来获取result
    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);
      //处理Transformation
      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;
  }

工作如下:

1.更新线程名称

2.调用hunt()方法获取请求结果

3.判断是否跳过MemoryCache,如果不跳过,那么就尝试从MemoryCache中获取数据。

4.然后调用Reqeust对应的ReqeustHandler去下载数据并解码为Bitmap

5.通知统计线程更新统计信息

6.如果需要Transformation或者旋转,那么则依次调用Transformation还有旋转

7.根据结果result派发dispatcher.dispatchFailed(this);或者dispatcher.dispatchComplete(this);

dispatcher.dispatchComplete经过层层调用,最后是调用到picasso.complete()方法,如下

  void complete(BitmapHunter hunter) {
    //获取Action
    Action single = hunter.getAction();
    //获取别添加的Action
    List<Action> joined = hunter.getActions();
    //是否有合并的Action
    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);
    }

    //有合并的Action
    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()方法
      action.complete(result, from);
      if (loggingEnabled) {
        log(OWNER_MAIN, VERB_COMPLETED, action.request.logId(), "from " + from);
      }
    } else {
      //失败则回调error()方法
      action.error();
      if (loggingEnabled) {
        log(OWNER_MAIN, VERB_ERRORED, action.request.logId());
      }
    }
  }

这里的Action实现类是ImageViewAction,我们去看看ImageViewAction的complete()的实现:

 @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来将bitmap设置到ImageView上
    PicassoDrawable.setBitmap(target, context, result, from, noFade, indicatorsEnabled);

    if (callback != null) {
      callback.onSuccess();
    }
  }

到这里就完成了整个Picasso加载图片的流程

说说其他需要注意的点

1.缓存策略

Picasso的缓存是内存缓存+磁盘缓存,内存缓存基于LruCache类,可以配置替换,磁盘缓存依赖于http缓存

内存缓存:

读缓存

前面提到的流程其实也说到会从缓存找

RequestCreator#into

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;
      }
    }

写缓存

在加载成功后,会有写入缓存的流程,代码如下

Dispatcher#performComplete

if (shouldWriteToMemoryCache(hunter.getMemoryPolicy())) {
      cache.set(hunter.getKey(), hunter.getResult());
}

磁盘缓存:

如果你是使用UrlConnectionDownloader的话,那很不幸,缓存只在Api>14上生效,因为缓存依赖于HttpResponseCache.
如果你依赖了okhttp,那么缓存策略始终是有效的。另外需要说明的是,既然是http缓存,那么缓存的可用性依赖于http响应是
否允许缓存,也就是说得看响应中是否携带Cache-Control、Expires等字段.

2关于清理线程

在Picasso初始化时候我们提到了一个清理线程,这个线程主要作用是找到那些Target已经被回收,但是对应的Request请求孩子继续的任务,找到后会取消对应的请求,避免资源浪费

  private static class CleanupThread extends Thread {
    private final ReferenceQueue<Object> referenceQueue;
    private final Handler handler;

    CleanupThread(ReferenceQueue<Object> referenceQueue, Handler handler) {
      this.referenceQueue = referenceQueue;
      this.handler = handler;
      setDaemon(true);
      setName(THREAD_PREFIX + "refQueue");
    }

    @Override public void run() {
      Process.setThreadPriority(THREAD_PRIORITY_BACKGROUND);
      while (true) {
        try {
          // Prior to Android 5.0, even when there is no local variable, the result from
          // remove() & obtainMessage() is kept as a stack local variable.
          // We're forcing this reference to be cleared and replaced by looping every second
          // when there is nothing to do.
          // This behavior has been tested and reproduced with heap dumps.
          RequestWeakReference<?> remove =
              (RequestWeakReference<?>) referenceQueue.remove(THREAD_LEAK_CLEANING_MS);
          Message message = handler.obtainMessage();
          if (remove != null) {
            message.what = REQUEST_GCED;
            message.obj = remove.action;
            handler.sendMessage(message);
          } else {
            message.recycle();
          }
        } catch (InterruptedException e) {
          break;
        } catch (final Exception e) {
          handler.post(new Runnable() {
            @Override public void run() {
              throw new RuntimeException(e);
            }
          });
          break;
        }
      }
    }

    void shutdown() {
      interrupt();
    }
  }

可以看到代码不断轮询ReferenceQueue,找到这样的reference,就交给handler,handler会从reference中拿到action,
并取消请求.

 case REQUEST_GCED: {
          Action action = (Action) msg.obj;
          if (action.getPicasso().loggingEnabled) {
            log(OWNER_MAIN, VERB_CANCELED, action.request.logId(), "target got garbage collected");
          }
          action.picasso.cancelExistingRequest(action.getTarget());
          break;
        }

3暂停与恢复请求

我们在开发过程中经常会使用到滑动不加载图片,不滑动才加载图片

pause:

Dispatcher#performPauseTag中遍历所有的hunter,都会调一次cancel,我们看下BitmapHunter#cancel方法的代码:

boolean cancel() {
     return action == null
         && (actions == null || actions.isEmpty())
         && future != null
         && future.cancel(false);
   }

注意到它会判断action是否为空,如果不为空就不会取消了。而在Dispatcher#performPauseTag中会把tag匹配的
action与对应的BitmapHunter解绑(detach),让BitmapHunter的action为空.所以这并不影响其他任务的执行。

resume

其实就是遍历pausedActions,挨个重新交给dispatcher分发。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266

推荐阅读更多精彩内容