天天看點

源碼閱讀系列:Picasso源碼閱讀Picasso初始化加載圖檔

源碼閱讀系列:Picasso源碼閱讀

  • 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加載圖檔的整個流程分析。代碼量适中,結構也比較清晰,适合閱讀學習。