源码阅读系列:Picasso源码阅读

Android开发中,我们经常用到各种开源框架,很多优秀的框架不仅提供了功能丰富的功能接口,其高超的代码编写和组织水平也值得我们学习。通过学习这些框架的源码,有助于快速提高我们的编程质量。在接下来的博客中,我将对一系列优秀的开源框架源码进行阅读分析,目的有两个,一是理解框架的实现机制,从源码的角度去分析怎样更好的使用这些框架。二是从这些优秀的源码中学习如何组织代码,如何实现高质量的编程。本文我们将分析Android图片加载工具Picasso源码。

我们从Picasso使用方式上入手,Picasso的使用通常分为两步,第一步初始化Picasso单例,第二步获取Picasso单例,创建RequestCreator,加载图片。代码示例如下:

Picasso初始化

private void initPicasso() {
    Picasso picasso = new Picasso.Builder(this)
            .defaultBitmapConfig(Bitmap.Config.RGB_565) // 设置全局的图片样式
            .downloader(new OkHttpDownloader(FileUtility.getPicassoCacheDir())) // 设置Downloader
            .requestTransformer(new Picasso.RequestTransformer() { // 设置RequestTransformer
                @Override
                public Request transformRequest(Request request) {
                    if (request.uri != null) {
                        return request.buildUpon().setUri(NetworkConfig.processUri(request.uri)).build();
                    }
                    return request;
                }
            })
            .build();
    Picasso.setSingletonInstance(picasso); // 设置Picasso单例
}

加载图片

Picasso.with(this) // 获取Picasso单例
        .load(url) // 返回一个新建的RequestCreator对象
        .resize(width, height) // 设置尺寸
        .onlyScaleDown() // 设置缩放
        .centerInside() // 设置裁剪方式
        .placeholder(R.drawable.transparent)  // 设置占位图片
        .error(R.drawable.group_chat_error_image)  // 设置出错展示的图片
        .memoryPolicy(MemoryPolicy.NO_CACHE) // 设置内存缓存策略
        .networkPolicy(NetworkPolicy.NO_CACHE) // 设置网络缓存策略
        .into(mScaleSampleImage, null);  // 设置图片加载的目标控件

Picasso初始化用到了单例模式和构造者模式。关于构造者模式的讲解可以查看这篇文章,此处不再赘述。在Picasso初始化用到Picasso.Builder静态内部类,有以下设置项:

public static class Builder {
    private final Context context;
    private Downloader downloader;
    private ExecutorService service;
    private Cache cache;
    private Listener listener;
    private RequestTransformer transformer;
    private List<RequestHandler> requestHandlers;
    private Bitmap.Config defaultBitmapConfig;

    private boolean indicatorsEnabled;
    private boolean loggingEnabled;

    // 设置图片格式
    public Builder defaultBitmapConfig(@NonNull Bitmap.Config bitmapConfig) {
        ...
    }
    // 设置Downloader
    public Builder downloader(@NonNull Downloader downloader) {
        ...
    }
    // 设置线程池
    public Builder executor(@NonNull ExecutorService executorService) {
        ...
    }
    // 设置内存缓存
    public Builder memoryCache(@NonNull Cache memoryCache) {
        ...
    }
    // 设置Picasso Listener,里面有响应函数onImageLoadFailed
    public Builder listener(@NonNull Listener listener) {
        ...
    }
    // 设置RequestTransformer,可以对网络请求添加统一处理
    public Builder requestTransformer(@NonNull RequestTransformer transformer) {
        ...
    }
    // 添加针对不同类型请求的Hander,请求类型如
    // 网络图片请求 http://example.com/1.png
    // 文件请求 file:///android_asset/foo/bar.png
    // 媒体库文件 content://media/external/images/media/1
    public Builder addRequestHandler(@NonNull RequestHandler requestHandler) {
        ...
    }
    // 设置是否展示调试指示器
    public Builder indicatorsEnabled(boolean enabled) {
        ...
    }
    // 设置是否启用日志
    public Builder loggingEnabled(boolean enabled) {
        ...
    }
    // 最终生成Picasso实例的build函数
    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);
    }

通过这个Builder类完成Picasso实例的构造,然后通过setSingletonInstance函数设置Picasso全局单例:

public class Picasso {
    static volatile Picasso singleton = null;
    ...
    public static void setSingletonInstance(@NonNull Picasso picasso) {
        if (picasso == null) {
          throw new IllegalArgumentException("Picasso must not be null.");
        }
        synchronized (Picasso.class) {
          if (singleton != null) {
          throw new IllegalStateException("Singleton instance already exists.");
        }
        singleton = picasso;
      }
    }
    ...
}

这样就完成了Picasso单例的初始化,并完成了一些全局的设置。接下来可以通过这个单例加载图片并展示了。

Picasso.with(this) // 获取Picasso单例
        .load(url) // 返回一个新建的RequestCreator对象
        .resize(width, height) // 设置尺寸
        .onlyScaleDown() // 设置缩放
        .centerInside() // 设置裁剪方式
        .placeholder(R.drawable.transparent)  // 设置占位图片
        .error(R.drawable.group_chat_error_image)  // 设置出错展示的图片
        .memoryPolicy(MemoryPolicy.NO_CACHE) // 设置内存缓存策略
        .networkPolicy(NetworkPolicy.NO_CACHE) // 设置网络缓存策略
        .into(mScaleSampleImage, null);  // 设置图片加载的目标控件

通过Picasso.with获取单例对象:

public class Picasso {
    static volatile Picasso singleton = null;
    ...
    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;
      }
    ...
}

获取到Picasso单例对象后,调用picasso.load函数,返回一个RequestCreator对象,该对象用于构造一个具体的加载图片请求Request。

public class Picasso {
    ...
    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));
    }

    public RequestCreator load(@NonNull File file) {
        if (file == null) {
          return new RequestCreator(this, null, 0);
        }
        return load(Uri.fromFile(file));
    }

    public RequestCreator load(@DrawableRes int resourceId) {
        if (resourceId == 0) {
          throw new IllegalArgumentException("Resource ID must not be zero.");
        }
        return new RequestCreator(this, null, resourceId);
    }
    ...
}

可以看出,load可以加载不同类型的资源,包括Uri,文件路径,文件,资源ID等。

RequestCreator采用了构造者模式,提供了一系列设置函数,可以设置本次要加载图片的裁剪方式,缩放方式,旋转角度等。

public class RequestCreator {
    ...
    private final Picasso picasso;
    private final Request.Builder data;

    ...
    private int placeholderResId;
    private int errorResId;
    private int memoryPolicy;
    private int networkPolicy;
    ...

    public RequestCreator placeholder(@DrawableRes int placeholderResId) {
        ...
    }

    public RequestCreator error(@DrawableRes int errorResId) {
    public RequestCreator tag(@NonNull Object tag) {
    public RequestCreator resize(int targetWidth, int targetHeight) {
    
    public RequestCreator centerCrop() {
        data.centerCrop(Gravity.CENTER);
        return this;
    }

    public RequestCreator centerInside() {
        data.centerInside();
        return this;
    }

    public RequestCreator onlyScaleDown() {
        data.onlyScaleDown();
        return this;
    }

    public RequestCreator rotate(float degrees) {
        data.rotate(degrees);
        return this;
    }

    public RequestCreator config(@NonNull Bitmap.Config config) {
        data.config(config);
        return this;
    }

    public RequestCreator priority(@NonNull Priority priority) {
        data.priority(priority);
        return this;
    }

    public RequestCreator transform(@NonNull Transformation transformation) {
        data.transform(transformation);
        return this;
    }

    public RequestCreator memoryPolicy(@NonNull MemoryPolicy policy,
      @NonNull MemoryPolicy... additional) {
        ...
    }
    public RequestCreator networkPolicy(@NonNull NetworkPolicy policy,
      @NonNull NetworkPolicy... additional) {
        ...
    }
    ...
}

RequestCreator对外提供了一系列设置函数,返回的都是同一个RequestCreator对象,标准的构造者模式。完成所有设置后,调用into函数实现Request对象的最终构造。

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;
    }
    // 第一个分支:延迟加载
    // deferred=true表明调用了fit()方法,根据ImageView的宽高适配图片
    // 所以需要在ImageView完成layout以后才能获得确切的尺寸
    // 所以需要延迟加载图片
    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);
    }

    // createRequest调用data.build()生成一个Request,
    // 并调用picasso.transformRequest对这个请求进行转换(如果设置了requestTransformer)
    Request request = createRequest(started);
    // 根据请求的图片和各个请求参数,如Uri,rotationDegrees,resize,centerCorp,centerInside等
    // 生成一个用于标识的字符串,作为缓存中的key
    String requestKey = createKey(request);

    // 第二个分支:从缓存中获取
    // 如果设置了缓存(通过memoryPolicy方法设置),先试图从缓存获取,获取成功直接返回
    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包含了complete/error/cancel等回调函数
    // 对应了图片加载成功,失败,取消加载的操作
    Action action =
        new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
            errorDrawable, requestKey, tag, callback, noFade);

    // 通过picasso对象将该action加入执行队列,里面的任务通过ThreadPoolExecutor线程池执行
    picasso.enqueueAndSubmit(action);
  }

这个函数是个很关键的函数,我们可以将它作为理解Picasso加载过程的一条主线。该函数首先通过checkMain检查是不是在主线程发起调用,由于加载图片需要对UI进行操作,所以必须在主线程进行函数的调用。

static void checkMain() {
    if (!isMain()) {
      throw new IllegalStateException("Method call should happen from the main thread.");
    }
}

static boolean isMain() {
    return Looper.getMainLooper().getThread() == Thread.currentThread();
}

checkMain的实现是通过比较当前线程和MainLooper线程是否是同一个线程进行的。
完成主线程检查后,判断有没有设置图片来源,包括Uri或Resource ID等,如果没设置不进行加载。

// 如果没有要加载的图片Uri或ResourceID,取消
    if (!data.hasImage()) {
      picasso.cancelRequest(target);
      if (setPlaceholder) {
        setPlaceholder(target, getPlaceholderDrawable());
      }
      return;
    }

接下来判断可以立即加载,还是需要延迟加载。延迟加载的场景是使用fit()方法进行图片尺寸自适应调整的时候。如果设置图片根据需要展示的View的尺寸进行自动调整,而且这个View的宽度或高度设置为0(比如通过weight进行相对宽高的设置),那么代码执行到这里的时候View可能还没完成测量的过程,还没有计算出实际的宽高,就需要等测量完成后才进行加载,也就是延迟加载,这里作为into函数三个分支的第一个分支。

延迟加载时通过DeferredRequestCreator类实现的:

class DeferredRequestCreator implements OnPreDrawListener, OnAttachStateChangeListener {
    private final RequestCreator creator;
    @VisibleForTesting final WeakReference<ImageView> target;
    @VisibleForTesting Callback callback;

    DeferredRequestCreator(RequestCreator creator, ImageView target, Callback callback) {
        this.creator = creator;
        this.target = new WeakReference<>(target);
        this.callback = callback;

        // 给目标View注册onAttachStateChangeListener
        target.addOnAttachStateChangeListener(this);

        // Only add the pre-draw listener if the view is already attached.
        // See: https://github.com/square/picasso/issues/1321
        if (target.getWindowToken() != null) {
          onViewAttachedToWindow(target);
        }
    }

    // 添加onAttachStateChangeListener的两个方法
    @Override public void onViewAttachedToWindow(View view) {
        view.getViewTreeObserver().addOnPreDrawListener(this);
    }
    // 添加onAttachStateChangeListener的两个方法
    @Override public void onViewDetachedFromWindow(View view) {
        view.getViewTreeObserver().removeOnPreDrawListener(this);
    }

    @Override public boolean onPreDraw() {
        ImageView target = this.target.get();
        if (target == null) {
          return true;
        }

        ViewTreeObserver vto = target.getViewTreeObserver();
        if (!vto.isAlive()) {
          return true;
        }

        int width = target.getWidth();
        int height = target.getHeight();

        if (width <= 0 || height <= 0 || target.isLayoutRequested()) {
            return true;
        }

        target.removeOnAttachStateChangeListener(this);
        vto.removeOnPreDrawListener(this);
        this.target.clear();

        // 通过unfit函数取消延迟加载的标识,通过resize设置尺寸,最后通过into函
        // 数生成最终的Request并提交到线程池去执行
        this.creator.unfit().resize(width, height).into(target, callback);
        return true;
    }
    ...
}

DeferredRequestCreator实现延迟加载,是通过给目标View注册onAttachStateChangeListener监听器实现的,监听器的两个接口函数onViewAttachedToWindow,onViewDetachedFromWindow分别对应了一个View被放置到界面上,和从界面上收回两个时间节点。在onViewAttachedToWindow中,给view的ViewTreeObserver添加onPreDrawListener监听器,并在onViewDetachedFromWindow中删除该监听器。onPreDrawListener监听器的onPreDraw接口函数会在界面完成测量后将要被展示出来前调用,此时可以获取到view的宽高,从而知道需要将加载的图片缩放到的具体尺寸。获取到具体尺寸后就可以通过unfit函数取消延迟加载的标识,通过resize设置尺寸,最后通过into函数生成最终的Request并提交到线程池去执行。

这是into函数里面需要延迟执行的情形的处理。如果没有通过fit进行自适应,而是一开始就指定了需要加载图片的宽高,就走第二个分支的逻辑,尝试从缓存获取。

    Request request = createRequest(started);
    // 根据请求的图片和各个请求参数,如Uri,rotationDegrees,resize,centerCorp,centerInside等
    // 生成一个用于标识的字符串,作为缓存中的key
    String requestKey = createKey(request);

    // 第二个分支:从缓存中获取
    // 如果设置了缓存(通过memoryPolicy方法设置),先试图从缓存获取,获取成功直接返回
    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;
      }
    }

createRequest会根据RequestCreator的各个设置项生成一个request,然后通过createKey生成一个key值:

private Request createRequest(long started) {
    int id = nextId.getAndIncrement();
    // data.build构造者模式
    Request request = data.build();
    request.id = id;
    request.started = started;

    boolean loggingEnabled = picasso.loggingEnabled;
    if (loggingEnabled) {
      log(OWNER_MAIN, VERB_CREATED, request.plainId(), request.toString());
    }
    // 如果设置了RequestTransformer则先transform一下request
    Request transformed = picasso.transformRequest(request);
    if (transformed != request) {
      // If the request was changed, copy over the id and timestamp from the original.
      transformed.id = id;
      transformed.started = started;

      if (loggingEnabled) {
        log(OWNER_MAIN, VERB_CHANGED, transformed.logId(), "into " + transformed);
      }
    }

    return transformed;
  }
static String createKey(Request data, StringBuilder builder) {
    if (data.stableKey != null) {
      builder.ensureCapacity(data.stableKey.length() + KEY_PADDING);
      builder.append(data.stableKey);
    } else if (data.uri != null) {
      String path = data.uri.toString();
      builder.ensureCapacity(path.length() + KEY_PADDING);
      builder.append(path);
    } else {
      builder.ensureCapacity(KEY_PADDING);
      builder.append(data.resourceId);
    }
    builder.append(KEY_SEPARATOR);

    if (data.rotationDegrees != 0) {
      builder.append("rotation:").append(data.rotationDegrees);
      if (data.hasRotationPivot) {
        builder.append('@').append(data.rotationPivotX).append('x').append(data.rotationPivotY);
      }
      builder.append(KEY_SEPARATOR);
    }
    if (data.hasSize()) {
      builder.append("resize:").append(data.targetWidth).append('x').append(data.targetHeight);
      builder.append(KEY_SEPARATOR);
    }
    if (data.centerCrop) {
      builder.append("centerCrop:").append(data.centerCropGravity).append(KEY_SEPARATOR);
    } else if (data.centerInside) {
      builder.append("centerInside").append(KEY_SEPARATOR);
    }

    if (data.transformations != null) {
      //noinspection ForLoopReplaceableByForEach
      for (int i = 0, count = data.transformations.size(); i < count; i++) {
        builder.append(data.transformations.get(i).key());
        builder.append(KEY_SEPARATOR);
      }
    }

    return builder.toString();
  }

从createKey的实现可以看出,同一个来源的图片,如果加载参数不同,会生成不同的key,并分别存储到缓存中。接下来判断是否设置了内存缓存,如果设置的话通过picasso.quickMemoryCacheCheck根据key查找缓存内容,找到的话返回这个bitmap,并设置给view。

public class Picasso {
    ...
    final Cache cache;
    ...
    Bitmap quickMemoryCacheCheck(String key) {
        // 从Cache中查找
        Bitmap cached = cache.get(key);
        if (cached != null) {
          stats.dispatchCacheHit();
        } else {
          stats.dispatchCacheMiss();
        }
        return cached;
        }
        ...
}

我们看看Cache类具体是怎样实现的:

public interface Cache {
    /** Retrieve an image for the specified {@code key} or {@code null}. */
    Bitmap get(String key);

    /** Store an image in the cache for the specified {@code key}. */
    void set(String key, Bitmap bitmap);

    /** Returns the current size of the cache in bytes. */
    int size();

    /** Returns the maximum size in bytes that the cache can hold. */
    int maxSize();

    /** Clears the cache. */
    void clear();

    /** Remove items whose key is prefixed with {@code keyPrefix}. */
    void clearKeyUri(String keyPrefix);

    /** A cache which does not store any values. */
    Cache NONE = new Cache() {
            @Override public Bitmap get(String key) {
            return null;
        }

        @Override public void set(String key, Bitmap bitmap) {
            // Ignore.
        }

        @Override public int size() {
            return 0;
        }

        @Override public int maxSize() {
            return 0;
        }

        @Override public void clear() {
        }

        @Override public void clearKeyUri(String keyPrefix) {
        }
    };
}

可以看到,Cache是一个接口类,规范了一系列对缓存的操作接口,包括get/set/size/clear等,还包含一个空实现。Picasso提供了一个实现了Cache接口的类LruCache,用户也可以提供自己的实现。

public class LruCache implements Cache {
    final LinkedHashMap<String, Bitmap> map;
    private final int maxSize;

    private int size;
    private int putCount;
    private int evictionCount;
  
    ...
    public LruCache(int maxSize) {
        if (maxSize <= 0) {
            throw new IllegalArgumentException("Max size must be positive.");
        }
        this.maxSize = maxSize;
        this.map = new LinkedHashMap<>(0, 0.75f, true);
    }

    @Override public Bitmap get(@NonNull String key) {
        if (key == null) {
            throw new NullPointerException("key == null");
        }

        Bitmap mapValue;
        synchronized (this) {
            mapValue = map.get(key);
            if (mapValue != null) {
                hitCount++;
                return mapValue;
            }
            missCount++;
        }

        return null;
    }

    @Override public void set(@NonNull String key, @NonNull Bitmap bitmap) {
        if (key == null || bitmap == null) {
            throw new NullPointerException("key == null || bitmap == null");
        }

        int addedSize = Utils.getBitmapBytes(bitmap);
        if (addedSize > maxSize) {
            return;
        }

        synchronized (this) {
            putCount++;
            size += addedSize;
            Bitmap previous = map.put(key, bitmap);
            if (previous != null) {
                size -= Utils.getBitmapBytes(previous);
            }
        }

        trimToSize(maxSize);
      }
    }

    private void trimToSize(int maxSize) {
        while (true) {
            String key;
            Bitmap value;
            synchronized (this) {
                if (size < 0 || (map.isEmpty() && size != 0)) {
                      throw new IllegalStateException(
                          getClass().getName() + ".sizeOf() is reporting inconsistent results!");
        }

        if (size <= maxSize || map.isEmpty()) {
            break;
        }

        // LinkedHashMap遍历输出的顺序跟元素插入的顺序相同,所以缓存的换出机制是FIFO
        Map.Entry<String, Bitmap> toEvict = map.entrySet().iterator().next();
        key = toEvict.getKey();
        value = toEvict.getValue();
        map.remove(key);
        size -= Utils.getBitmapBytes(value);
        evictionCount++;
      }
    }
  }
    ...
}

LruCache通过一个LinkedHashMap来存储图片键值对,LinkedHashMap结合了链表的FIFO特性以及HashMap的键值对存取特性,通过iterator遍历的时候保证先加入的先遍历到,当缓存的大小达到设定值的时候,通过trimToSize函数进行缓存的换出,借助LinkedHashMap实现FIFO的换出策略。同时注意由于多个线程可以同时存取缓存,需要进行线程同步机制,这里是通过synchronized加锁实现的。

如果缓存没有命中,进入into函数第三个分支,通过网络或文件系统加载。

    // 第三个分支:从网络或文件系统加载
    // 如果从缓存获取失败,则生成一个Action来加载该图片。
    // 一个Action包含了complete/error/cancel等回调函数
    // 对应了图片加载成功,失败,取消加载的操作
    Action action =
        new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
            errorDrawable, requestKey, tag, callback, noFade);

    // 通过picasso对象将该action加入执行队列,里面的任务通过ThreadPoolExecutor线程池执行
    picasso.enqueueAndSubmit(action);

这里一次图片加载的操作是通过一个Action来表示的,Action是一个接口类,提供了跟一次图片加载相关的操作,比如请求的Request,网络缓存策略,内存缓存策略,加载成功的回调函数,失败的回调,取消的回调等。

abstract class Action<T> {
    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;
      }
    }

    final Picasso picasso;
    final Request request;
    final WeakReference<T> target;

    abstract void complete(Bitmap result, Picasso.LoadedFrom from);
    abstract void error(Exception e);
    void cancel() {
        cancelled = true;
    }
    ...
}

Picasso提供了几种Action的实现,包括ImageViewAction(图片加载并展示到ImageView),NotificationAction(图片加载并展示到Notification),GetAction(图片同步加载不展示),FetchAction(图片异步加载并设置回调函数)等,下面给出ImageViewAction的代码:

class ImageViewAction extends Action<ImageView> {

    Callback callback;

    ImageViewAction(Picasso picasso, ImageView imageView, Request data, int memoryPolicy,
      int networkPolicy, int errorResId, Drawable errorDrawable, String key, Object tag,
      Callback callback, boolean noFade) {
        super(picasso, imageView, data, memoryPolicy, networkPolicy, errorResId, errorDrawable, key,
        tag, noFade);
        this.callback = callback;
    }

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

    @Override public void error(Exception e) {
        ImageView target = this.target.get();
        if (target == null) {
            return;
        }
        Drawable placeholder = target.getDrawable();
        if (placeholder instanceof AnimationDrawable) {
            ((AnimationDrawable) placeholder).stop();
        }
        if (errorResId != 0) {
          target.setImageResource(errorResId);
        } else if (errorDrawable != null) {
          target.setImageDrawable(errorDrawable);
        }

        if (callback != null) {
            callback.onError(e);
        }
    }

    @Override void cancel() {
        super.cancel();
        if (callback != null) {
            callback = null;
        }
    }
}

构造完Action通过picasso对象加入线程池执行:

    // 通过picasso对象将该action加入执行队列,里面的任务通过ThreadPoolExecutor线程池执行
    picasso.enqueueAndSubmit(action);
public class Picasso {
    ...
    final Dispatcher dispatcher;
    ...
    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);
    }
    ...
}

Picasso调用Dispatcher类进行消息的分发:

class Dispatcher {
    ...
    final Handler handler;
    ...
    Dispatcher(Context context, ExecutorService service, Handler mainThreadHandler,
          Downloader downloader, Cache cache, Stats stats) {
        ...
        this.handler = new DispatcherHandler(dispatcherThread.getLooper(), this);
        ...
    }
    void dispatchSubmit(Action action) {
        handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));
    }
    ...
}

DispatcherHandler提供对各种动作的响应,包括提交一个Action,取消Action,暂停等等。

private static class DispatcherHandler extends Handler {
    private final Dispatcher dispatcher;

    public DispatcherHandler(Looper looper, Dispatcher dispatcher) {
      super(looper);
      this.dispatcher = dispatcher;
    }

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

我们看一下提交一个Action最终是怎样得到执行的:

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;
    }
    // 根据每个Action创建一个Hunter对象,并通过ExecutorService提交到线程池执行
    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());
    }
  }

可以看到performSubmit函数会根据每个Action创建一个BitmapHunter对象,并通过ExecutorService提交到线程池执行。BitmapHunter是一个多线程类,提供了加载图片的操作:

class BitmapHunter implements Runnable {
    @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 (NetworkRequestHandler.ResponseException e) {
          if (!NetworkPolicy.isOfflineOnly(e.networkPolicy) || e.code != 504) {
            exception = e;
          }
          dispatcher.dispatchFailed(this);
        }  
        ...
    }
    ...
}

看一下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.load进行加载
    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) {
        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) {
          }
        }
      }
    }

    if (bitmap != null) {
      if (picasso.loggingEnabled) {
        log(OWNER_HUNTER, VERB_DECODED, data.logId());
      }
      stats.dispatchBitmapDecoded(bitmap);
      // 如果设置了对bitmap的transform函数,执行transform操作
      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);
        }
      }
    }
    // 完成加载成功的bitmap
    return bitmap;
  }

再次尝试从内存缓存获取,之前没再内存缓存中,说不定这时候已经在了。如果获取不到,调用RequestHandler的load函数进行真正的加载操作。

RequestHandler是个虚基类,提供了统一的加载接口:

public abstract class RequestHandler {
    ...
    @Nullable public Bitmap getBitmap() {
      return bitmap;
    }
    @Nullable public abstract Result load(Request request, int networkPolicy) throws IOException;
    ...
}

NetworkRequestHandler,ContactsPhotoRequestHandler,AssetRequestHandler,ContentStreamRequestHandler,ResourceRequestHandler等都实现了RequestHandler基类,分别提供了网络加载,联系人图片加载,Asset资源加载,文件加载,Resource资源图片加载等不同的加载方式。

这样,就完成了Picasso加载图片的整个流程分析。代码量适中,结构也比较清晰,适合阅读学习。

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

推荐阅读更多精彩内容