Picasso作为图片处理的主流库之一,非常有名,今天我们就从源码的层面上解析他。
首先是picasso的典型用法:

Picasso.with(context)
    .load(url)
    .into(imageView); 

Picasso.with(context)
    .load(url)
    .resize(width,height)
    .centerInside().into(imageView);

Picasso .with(context)
    .load(url)
    .placeholder(R.drawable.loading)
    .error(R.drawable.error)
    .into(imageView);

可以看到,非常简单。那么我们就从这些调用入手逐步查看代码。

初始化

Picasso.with(@NonNull Context context):

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

可以看到几点信息:
1.static方法,使用起来很方便,屏蔽了大量的参数,让他们在后面逐步加入;
2.整个Picasso采用单例模式,Picasso的设计就是承担很多工作的引擎,因此占用资源较多,没有必要在一个app中出现多个,也为了节省资源和提高效率,采用了单例模式;
3.创建单例的实例的时候,new出了Builder,并传入context,之后调用Builder的build来建立单例;
4.使用synchronized来保证建立单例实例的过程是线程安全的;

简单看下build方法:

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对象实例真正创建的地方。那么之前的这些操作是在初始化环境:
1.downloader下载器的建立;
2.cache的建立;
3.service线程池的建立;
4.RequestTransformer的建立;
再从结构上看,可以看出Picasso的单例的创建采用的是build模式。如果哪天想修改Picasso的上述组件的设置,又不想暴露给调用者,那么就可以再写一个build,重写这些代码并替换相关组件,同时在with层面上修改调用即可。

下面再来看看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<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);

    this.stats = stats;
    this.targetToAction = new WeakHashMap<Object, Action>();
    this.targetToDeferredRequestCreator = new WeakHashMap<ImageView, DeferredRequestCreator>();
    this.indicatorsEnabled = indicatorsEnabled;
    this.loggingEnabled = loggingEnabled;
    this.referenceQueue = new ReferenceQueue<Object>();
    this.cleanupThread = new CleanupThread(referenceQueue, HANDLER);
    this.cleanupThread.start();
  }

建立了allRequestHandlers,默认提供7个,另外还可建立扩展,扩展是可以从构造传递过来参数建立的。这里只简单看下requestHandler,以FileRequestHandler为例:

class FileRequestHandler extends ContentStreamRequestHandler {

  FileRequestHandler(Context context) {
    super(context);
  }

  @Override public boolean canHandleRequest(Request data) {
    return SCHEME_FILE.equals(data.uri.getScheme());
  }

  @Override public Result load(Request request, int networkPolicy) throws IOException {
    return new Result(null, getInputStream(request), DISK, getFileExifRotation(request.uri));
  }

  static int getFileExifRotation(Uri uri) throws IOException {
    ExifInterface exifInterface = new ExifInterface(uri.getPath());
    return exifInterface.getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL);
  }
}

可以看到,FileRequestHandler是处理请求的辅助的角色,;load里面的result加载的方式是disk,基本可以确定是直接从磁盘上读取文件。后面还会有调用,这里暂时不再详述。
再回到Picasso的构造,注意:requestHandlers = Collections.unmodifiableList(allRequestHandlers);这句话是重构容器,并生成一个只读不可写的容器对象。也就是说,一旦开始Picasso就确定的这些requesthandler,在运行期间不可再扩展添加。
再看cleanupThread:

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

一个死循环,不断的从referenceQueue队列中移除request,然后对主线程的handler发送gced的消息。这个线程就是一个垃圾回收的线程。
至此,初始化的过程结束了。

参数设置

随便看下load函数:

public RequestCreator load(@Nullable Uri uri) {
    return new RequestCreator(this, uri, 0);
  }

非常简单,只是创建并返回了一个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);
  }

最重要的是产生了一个Request.Builder,为后面建立request做准备。
回到load调用,因为返回的是RequestCreator对象,因此后续的处理都是针对他的,例如resize方法:

public RequestCreator resize(int targetWidth, int targetHeight) {
    data.resize(targetWidth, targetHeight);
    return this;
  }

resize实际上是在调用data也就是Request.Builder的resize方法处理图片的大小设置。再进一步看下去:

public Builder resize(int targetWidth, int targetHeight) {
      if (targetWidth < 0) {
        throw new IllegalArgumentException("Width must be positive number or 0.");
      }
      if (targetHeight < 0) {
        throw new IllegalArgumentException("Height must be positive number or 0.");
      }
      if (targetHeight == 0 && targetWidth == 0) {
        throw new IllegalArgumentException("At least one dimension has to be positive number.");
      }
      this.targetWidth = targetWidth;
      this.targetHeight = targetHeight;
      return this;
    }

只是将宽高的参数保留起来。看到这里大体能够明白picasso的一个操作逻辑了,前期的这些设置都是作为参数保留下来的,只有最后真正执行的时候再读取这些参数进行相应的操作。那么这种模式可以理解为将复杂的非常多的参数进行了链式的保存和归类,便于调用者的理解和操作简化,需要的进行设置,不需要的跳过。每次进行设置都返回RequestCreator。
那么要在什么地方进行实际的操作呢?我们下面来看into。

实际请求

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

这段代码最后要调用picasso.enqueueAndSubmit(action);就是实际提交请求了。后面我们再进去具体看。setPlaceholder进行占位符的判断,deferred用来进行是否延迟加载的判定,shouldReadFromMemoryCache来确定缓存加载策略并执行相关逻辑。最后创建一个Action,并提交这个action。
首先我们来看看action,代码就不贴了,基本上就是个容器类,用来存储请求的一些信息,并且是个抽象类。需要注意的是对target的保存,使用的是弱引用,为了不造成内存泄露。这个target就是要显示图片的view。action的子类承担的工作都是下载图片等,需要覆盖几个抽象方法来处理完成(设置view图像)、错误和取消等情况。那么几乎可以肯定大部分的真正的走网处理都在picasso.enqueueAndSubmit(action);里面了。这里回顾下,这种设计方式将请求作为了一连串的参数数据保存在action里,执行在另外的地方做,就是一个基本的数据与逻辑的分离,解耦。能够将逻辑的处理标准化,而数据的样式可以随着扩展多样化。
下面继续看enqueueAndSubmit:

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

最主要的干了一件事:submit,那么这个submit做了什么呢?

void submit(Action action) {
    dispatcher.dispatchSubmit(action);
  }

到达这里,进入了Dispatcher,Dispatcher在build的初始化阶段就建立好了,是进行action派发的机构。

void dispatchSubmit(Action action) {
    handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));
  }

利用handler将action发送了出去,那么看看handler,是个DispatcherHandler,里面的最重要的handleMessage,根据参数不同做出了相关处理:

@Override public void handleMessage(final Message msg) {
      switch (msg.what) {
        case REQUEST_SUBMIT: {
          Action action = (Action) msg.obj;
          dispatcher.performSubmit(action);
          break;
        }
        case REQUEST_CANCEL: {
          Action action = (Action) msg.obj;
          dispatcher.performCancel(action);
          break;
        }
        case TAG_PAUSE: {
          Object tag = msg.obj;
          dispatcher.performPauseTag(tag);
          break;
        }
        case TAG_RESUME: {
          Object tag = msg.obj;
          dispatcher.performResumeTag(tag);
          break;
        }
        case HUNTER_COMPLETE: {
          BitmapHunter hunter = (BitmapHunter) msg.obj;
          dispatcher.performComplete(hunter);
          break;
        }
        case HUNTER_RETRY: {
          BitmapHunter hunter = (BitmapHunter) msg.obj;
          dispatcher.performRetry(hunter);
          break;
        }
        case HUNTER_DECODE_FAILED: {
          BitmapHunter hunter = (BitmapHunter) msg.obj;
          dispatcher.performError(hunter, false);
          break;
        }
        case HUNTER_DELAY_NEXT_BATCH: {
          dispatcher.performBatchComplete();
          break;
        }
        case NETWORK_STATE_CHANGE: {
          NetworkInfo info = (NetworkInfo) msg.obj;
          dispatcher.performNetworkStateChange(info);
          break;
        }
        case AIRPLANE_MODE_CHANGE: {
          dispatcher.performAirplaneModeChange(msg.arg1 == AIRPLANE_MODE_ON);
          break;
        }
        default:
          Picasso.HANDLER.post(new Runnable() {
            @Override public void run() {
              throw new AssertionError("Unknown handler message received: " + msg.what);
            }
          });
      }

这个dispatcher就是Dispatcher的引用,实际上最后还是在调用Dispatcher,但为什么绕这个圈呢?原因在于:

this.dispatcherThread = new DispatcherThread();
this.dispatcherThread.start();
...
this.handler = new DispatcherHandler(dispatcherThread.getLooper(), this);

看到了吧,这里用了DispatcherThread(HandlerThread的子类),并且将looper传递给了DispatcherHandler。也就是说,DispatcherHandler的处理过程运行在了其他线程里,作为异步操作了,包括调用的Dispatcher的dispatcher.performSubmit(action);等方法都是如此。这里巧妙的运用了DispatcherThread实现了异步线程操作,避免了ui线程的等待。那么HandlerThread是什么呢?简单的讲就是带有消息循环looper的线程,会不断的处理消息。那么这么分离使action的处理都独立到了线程中。
下面来看Dispatcher的performSubmit:

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

1.是否该请求被暂停,如果是放入暂停action的map里;
2.从hunterMap中查找是否已经有相同uri的BitmapHunter,如果有合并返回;
3.通过forRequest创建hunter;
4.提交线程池,并加入hunterMap中;
重点在于forRequest和提交线程池。先看下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);
  }

1.从action中获得request;
2.根据request依次到requestHandlers中的每个requestHandler判断是否可处理(还记得requestHandlers一共默认有7个,还可扩展);
3.如果可被一个requestHandler处理,则new出BitmapHunter,并传递这个requestHandler进入;
这里的处理方式是个标准的链式,依次询问每个处理者是否可以,可以交付,不可以继续。非常适合少量的处理者,并且请求和处理者是一对一关系的情况。

下面回来看线程池,service.submit(hunter);,这个BitmapHunter是个runnable,提交后就会在线程池分配的线程中运行hunter的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
    ...
  }

1.更新线程名字,这里需要注意的是NAME_BUILDER,是个ThreadLocal对象,就是会为每个线程分离出一个对象,防止并发线程改写该对象造成的数据错乱,具体概念不说了,可以具体查查看。
2.调用hunt方法返回结果,重点,一会儿看;
3.调用dispatcher.dispatchComplete(this);或dispatcher.dispatchFailed(this);进行收尾的处理;
4.异常处理;
下面看看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);
    if (result != null) {
      loadedFrom = result.getLoadedFrom();
      exifOrientation = 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() || 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;
  }

1.根据策略检查是否可直接从内存中获取,如果可以加载并返回;
2.通过requestHandler.load(data, networkPolicy);去获取返回数据。重点;
3.根据之前设置的参数处理Transformation;

从requestHandler.load看起,requestHandler是个抽象类,那么我们就从NetworkRequestHandler这个比较常用的子类看起,看他的load方法:

@Override @Nullable 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);
  }

1.通过downloader.load进行了下载活动,重点;
2.根据response.cached确定从磁盘或网络加载;
3.如果是网络加载,需要走dispatchDownloadFinished,里面发送了DOWNLOAD_FINISHED请求,告知下载完成;

下面进入到downloader了,Downloader又是个抽象类,实现有3个,OkHttp3Downloader、OkHttpDownloader、UrlConnectionDownloader。默认>9以上使用OkHttp3Downloader,备用使用OkHttpDownloader,都不行使用UrlConnectionDownloader。我们以OkHttp3Downloader为例看看:

@Override public Response load(@NonNull Uri uri, int networkPolicy) throws IOException {
    CacheControl cacheControl = null;
    if (networkPolicy != 0) {
      if (NetworkPolicy.isOfflineOnly(networkPolicy)) {
        cacheControl = CacheControl.FORCE_CACHE;
      } else {
        CacheControl.Builder builder = new CacheControl.Builder();
        if (!NetworkPolicy.shouldReadFromDiskCache(networkPolicy)) {
          builder.noCache();
        }
        if (!NetworkPolicy.shouldWriteToDiskCache(networkPolicy)) {
          builder.noStore();
        }
        cacheControl = builder.build();
      }
    }

    Request.Builder builder = new okhttp3.Request.Builder().url(uri.toString());
    if (cacheControl != null) {
      builder.cacheControl(cacheControl);
    }

    okhttp3.Response response = client.newCall(builder.build()).execute();
    int responseCode = response.code();
    if (responseCode >= 300) {
      response.body().close();
      throw new ResponseException(responseCode + " " + response.message(), networkPolicy,
          responseCode);
    }

    boolean fromCache = response.cacheResponse() != null;

    ResponseBody responseBody = response.body();
    return new Response(responseBody.byteStream(), fromCache, responseBody.contentLength());
  }

1.检查网络策略,如果需要从缓存里拿;
2.标准的okhttp使用下载图片;

最后回来看下Dispatcher的dispatchComplete方法,会给ThreadHandler发送HUNTER_COMPLETE消息,而在handleMessage里面会最终走到dispatcher.performComplete(hunter);

void performComplete(BitmapHunter hunter) {
    if (shouldWriteToMemoryCache(hunter.getMemoryPolicy())) {
      cache.set(hunter.getKey(), hunter.getResult());
    }
    hunterMap.remove(hunter.getKey());
    batch(hunter);
    if (hunter.getPicasso().loggingEnabled) {
      log(OWNER_DISPATCHER, VERB_BATCHED, getLogIdsForHunter(hunter), "for completion");
    }
  }

1.写缓存;
2.从hunterMap中移除本次hunter;
3.batch(hunter);内部是延迟发送了一个HUNTER_DELAY_NEXT_BATCH消息;
在handlehandleMessage里面走的是dispatcher.performBatchComplete();注意到此为止都在异步线程中运作。看看这个函数:

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

往主线程发送了HUNTER_BATCH_COMPLETE。在Picasso的主线程handler中的处理是:

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

最终是走到了Picasso的complete方法中,这里实际上处理了完成的hunter。complete的关键就是一句话:deliverAction调用,而这里的关键是action.complete(result, from);一个抽象方法,最后看看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);

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

不用再解释什么了吧。这弯儿绕的。
至此分析完毕。

写在最后

参数的设置过程和分类很好,除了主线程外,起了一个线程用来处理dispicher,没有使用并发,而是使用looper线程,后面采用线程池进行下载的操作。各个环节扩展性都很好,action/requesthander/downloader等。有兴趣的可以再看看这里的LruCache,对LinkedHashMap的使用也是不错的。


机械面条
77 声望31 粉丝