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

Android開(kāi)發(fā)中,我們經(jīng)常用到各種開(kāi)源框架,很多優(yōu)秀的框架不僅提供了功能豐富的功能接口,其高超的代碼編寫(xiě)和組織水平也值得我們學(xué)習(xí)。通過(guò)學(xué)習(xí)這些框架的源碼,有助于快速提高我們的編程質(zhì)量。在接下來(lái)的博客中,我將對(duì)一系列優(yōu)秀的開(kāi)源框架源碼進(jìn)行閱讀分析,目的有兩個(gè),一是理解框架的實(shí)現(xiàn)機(jī)制,從源碼的角度去分析怎樣更好的使用這些框架。二是從這些優(yōu)秀的源碼中學(xué)習(xí)如何組織代碼,如何實(shí)現(xiàn)高質(zhì)量的編程。本文我們將分析Android圖片加載工具Picasso源碼。

我們從Picasso使用方式上入手,Picasso的使用通常分為兩步,第一步初始化Picasso單例,第二步獲取Picasso單例,創(chuàng)建RequestCreator,加載圖片。代碼示例如下:

Picasso初始化

private void initPicasso() {
    Picasso picasso = new Picasso.Builder(this)
            .defaultBitmapConfig(Bitmap.Config.RGB_565) // 設(shè)置全局的圖片樣式
            .downloader(new OkHttpDownloader(FileUtility.getPicassoCacheDir())) // 設(shè)置Downloader
            .requestTransformer(new Picasso.RequestTransformer() { // 設(shè)置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); // 設(shè)置Picasso單例
}

加載圖片

Picasso.with(this) // 獲取Picasso單例
        .load(url) // 返回一個(gè)新建的RequestCreator對(duì)象
        .resize(width, height) // 設(shè)置尺寸
        .onlyScaleDown() // 設(shè)置縮放
        .centerInside() // 設(shè)置裁剪方式
        .placeholder(R.drawable.transparent)  // 設(shè)置占位圖片
        .error(R.drawable.group_chat_error_image)  // 設(shè)置出錯(cuò)展示的圖片
        .memoryPolicy(MemoryPolicy.NO_CACHE) // 設(shè)置內(nèi)存緩存策略
        .networkPolicy(NetworkPolicy.NO_CACHE) // 設(shè)置網(wǎng)絡(luò)緩存策略
        .into(mScaleSampleImage, null);  // 設(shè)置圖片加載的目標(biāo)控件

Picasso初始化用到了單例模式和構(gòu)造者模式。關(guān)于構(gòu)造者模式的講解可以查看這篇文章,此處不再贅述。在Picasso初始化用到Picasso.Builder靜態(tài)內(nèi)部類(lèi),有以下設(shè)置項(xiàng):

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;

    // 設(shè)置圖片格式
    public Builder defaultBitmapConfig(@NonNull Bitmap.Config bitmapConfig) {
        ...
    }
    // 設(shè)置Downloader
    public Builder downloader(@NonNull Downloader downloader) {
        ...
    }
    // 設(shè)置線程池
    public Builder executor(@NonNull ExecutorService executorService) {
        ...
    }
    // 設(shè)置內(nèi)存緩存
    public Builder memoryCache(@NonNull Cache memoryCache) {
        ...
    }
    // 設(shè)置Picasso Listener,里面有響應(yīng)函數(shù)onImageLoadFailed
    public Builder listener(@NonNull Listener listener) {
        ...
    }
    // 設(shè)置RequestTransformer,可以對(duì)網(wǎng)絡(luò)請(qǐng)求添加統(tǒng)一處理
    public Builder requestTransformer(@NonNull RequestTransformer transformer) {
        ...
    }
    // 添加針對(duì)不同類(lèi)型請(qǐng)求的Hander,請(qǐng)求類(lèi)型如
    // 網(wǎng)絡(luò)圖片請(qǐng)求 http://example.com/1.png
    // 文件請(qǐng)求 file:///android_asset/foo/bar.png
    // 媒體庫(kù)文件 content://media/external/images/media/1
    public Builder addRequestHandler(@NonNull RequestHandler requestHandler) {
        ...
    }
    // 設(shè)置是否展示調(diào)試指示器
    public Builder indicatorsEnabled(boolean enabled) {
        ...
    }
    // 設(shè)置是否啟用日志
    public Builder loggingEnabled(boolean enabled) {
        ...
    }
    // 最終生成Picasso實(shí)例的build函數(shù)
    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);
    }

通過(guò)這個(gè)Builder類(lèi)完成Picasso實(shí)例的構(gòu)造,然后通過(guò)setSingletonInstance函數(shù)設(shè)置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單例的初始化,并完成了一些全局的設(shè)置。接下來(lái)可以通過(guò)這個(gè)單例加載圖片并展示了。

Picasso.with(this) // 獲取Picasso單例
        .load(url) // 返回一個(gè)新建的RequestCreator對(duì)象
        .resize(width, height) // 設(shè)置尺寸
        .onlyScaleDown() // 設(shè)置縮放
        .centerInside() // 設(shè)置裁剪方式
        .placeholder(R.drawable.transparent)  // 設(shè)置占位圖片
        .error(R.drawable.group_chat_error_image)  // 設(shè)置出錯(cuò)展示的圖片
        .memoryPolicy(MemoryPolicy.NO_CACHE) // 設(shè)置內(nèi)存緩存策略
        .networkPolicy(NetworkPolicy.NO_CACHE) // 設(shè)置網(wǎng)絡(luò)緩存策略
        .into(mScaleSampleImage, null);  // 設(shè)置圖片加載的目標(biāo)控件

通過(guò)Picasso.with獲取單例對(duì)象:

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) {
            // 如果還沒(méi)初始化,采用默認(rèn)配置進(jìn)行初始化
            if (singleton == null) {
              singleton = new Builder(context).build();
            }
          }
        }
        return singleton;
      }
    ...
}

獲取到Picasso單例對(duì)象后,調(diào)用picasso.load函數(shù),返回一個(gè)RequestCreator對(duì)象,該對(duì)象用于構(gòu)造一個(gè)具體的加載圖片請(qǐng)求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可以加載不同類(lèi)型的資源,包括Uri,文件路徑,文件,資源ID等。

RequestCreator采用了構(gòu)造者模式,提供了一系列設(shè)置函數(shù),可以設(shè)置本次要加載圖片的裁剪方式,縮放方式,旋轉(zhuǎn)角度等。

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對(duì)外提供了一系列設(shè)置函數(shù),返回的都是同一個(gè)RequestCreator對(duì)象,標(biāo)準(zhǔn)的構(gòu)造者模式。完成所有設(shè)置后,調(diào)用into函數(shù)實(shí)現(xiàn)Request對(duì)象的最終構(gòu)造。

public void into(ImageView target, Callback callback) {
    long started = System.nanoTime();
    // 檢查是否是主線程調(diào)用,必須在主線程調(diào)用
    checkMain();

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

    // 如果沒(méi)有要加載的圖片Uri或ResourceID,取消
    if (!data.hasImage()) {
      picasso.cancelRequest(target);
      if (setPlaceholder) {
        setPlaceholder(target, getPlaceholderDrawable());
      }
      return;
    }
    // 第一個(gè)分支:延遲加載
    // deferred=true表明調(diào)用了fit()方法,根據(jù)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調(diào)用data.build()生成一個(gè)Request,
    // 并調(diào)用picasso.transformRequest對(duì)這個(gè)請(qǐng)求進(jìn)行轉(zhuǎn)換(如果設(shè)置了requestTransformer)
    Request request = createRequest(started);
    // 根據(jù)請(qǐng)求的圖片和各個(gè)請(qǐng)求參數(shù),如Uri,rotationDegrees,resize,centerCorp,centerInside等
    // 生成一個(gè)用于標(biāo)識(shí)的字符串,作為緩存中的key
    String requestKey = createKey(request);

    // 第二個(gè)分支:從緩存中獲取
    // 如果設(shè)置了緩存(通過(guò)memoryPolicy方法設(shè)置),先試圖從緩存獲取,獲取成功直接返回
    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());
    }

    // 第三個(gè)分支:從網(wǎng)絡(luò)或文件系統(tǒng)加載
    // 如果從緩存獲取失敗,則生成一個(gè)Action來(lái)加載該圖片。
    // 一個(gè)Action包含了complete/error/cancel等回調(diào)函數(shù)
    // 對(duì)應(yīng)了圖片加載成功,失敗,取消加載的操作
    Action action =
        new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
            errorDrawable, requestKey, tag, callback, noFade);

    // 通過(guò)picasso對(duì)象將該action加入執(zhí)行隊(duì)列,里面的任務(wù)通過(guò)ThreadPoolExecutor線程池執(zhí)行
    picasso.enqueueAndSubmit(action);
  }

這個(gè)函數(shù)是個(gè)很關(guān)鍵的函數(shù),我們可以將它作為理解Picasso加載過(guò)程的一條主線。該函數(shù)首先通過(guò)checkMain檢查是不是在主線程發(fā)起調(diào)用,由于加載圖片需要對(duì)UI進(jìn)行操作,所以必須在主線程進(jìn)行函數(shù)的調(diào)用。

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的實(shí)現(xiàn)是通過(guò)比較當(dāng)前線程和MainLooper線程是否是同一個(gè)線程進(jìn)行的。
完成主線程檢查后,判斷有沒(méi)有設(shè)置圖片來(lái)源,包括Uri或Resource ID等,如果沒(méi)設(shè)置不進(jìn)行加載。

// 如果沒(méi)有要加載的圖片Uri或ResourceID,取消
    if (!data.hasImage()) {
      picasso.cancelRequest(target);
      if (setPlaceholder) {
        setPlaceholder(target, getPlaceholderDrawable());
      }
      return;
    }

接下來(lái)判斷可以立即加載,還是需要延遲加載。延遲加載的場(chǎng)景是使用fit()方法進(jìn)行圖片尺寸自適應(yīng)調(diào)整的時(shí)候。如果設(shè)置圖片根據(jù)需要展示的View的尺寸進(jìn)行自動(dòng)調(diào)整,而且這個(gè)View的寬度或高度設(shè)置為0(比如通過(guò)weight進(jìn)行相對(duì)寬高的設(shè)置),那么代碼執(zhí)行到這里的時(shí)候View可能還沒(méi)完成測(cè)量的過(guò)程,還沒(méi)有計(jì)算出實(shí)際的寬高,就需要等測(cè)量完成后才進(jìn)行加載,也就是延遲加載,這里作為into函數(shù)三個(gè)分支的第一個(gè)分支。

延遲加載時(shí)通過(guò)DeferredRequestCreator類(lèi)實(shí)現(xiàn)的:

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;

        // 給目標(biāo)View注冊(cè)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的兩個(gè)方法
    @Override public void onViewAttachedToWindow(View view) {
        view.getViewTreeObserver().addOnPreDrawListener(this);
    }
    // 添加onAttachStateChangeListener的兩個(gè)方法
    @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();

        // 通過(guò)unfit函數(shù)取消延遲加載的標(biāo)識(shí),通過(guò)resize設(shè)置尺寸,最后通過(guò)into函
        // 數(shù)生成最終的Request并提交到線程池去執(zhí)行
        this.creator.unfit().resize(width, height).into(target, callback);
        return true;
    }
    ...
}

DeferredRequestCreator實(shí)現(xiàn)延遲加載,是通過(guò)給目標(biāo)View注冊(cè)onAttachStateChangeListener監(jiān)聽(tīng)器實(shí)現(xiàn)的,監(jiān)聽(tīng)器的兩個(gè)接口函數(shù)onViewAttachedToWindow,onViewDetachedFromWindow分別對(duì)應(yīng)了一個(gè)View被放置到界面上,和從界面上收回兩個(gè)時(shí)間節(jié)點(diǎn)。在onViewAttachedToWindow中,給view的ViewTreeObserver添加onPreDrawListener監(jiān)聽(tīng)器,并在onViewDetachedFromWindow中刪除該監(jiān)聽(tīng)器。onPreDrawListener監(jiān)聽(tīng)器的onPreDraw接口函數(shù)會(huì)在界面完成測(cè)量后將要被展示出來(lái)前調(diào)用,此時(shí)可以獲取到view的寬高,從而知道需要將加載的圖片縮放到的具體尺寸。獲取到具體尺寸后就可以通過(guò)unfit函數(shù)取消延遲加載的標(biāo)識(shí),通過(guò)resize設(shè)置尺寸,最后通過(guò)into函數(shù)生成最終的Request并提交到線程池去執(zhí)行。

這是into函數(shù)里面需要延遲執(zhí)行的情形的處理。如果沒(méi)有通過(guò)fit進(jìn)行自適應(yīng),而是一開(kāi)始就指定了需要加載圖片的寬高,就走第二個(gè)分支的邏輯,嘗試從緩存獲取。

    Request request = createRequest(started);
    // 根據(jù)請(qǐng)求的圖片和各個(gè)請(qǐng)求參數(shù),如Uri,rotationDegrees,resize,centerCorp,centerInside等
    // 生成一個(gè)用于標(biāo)識(shí)的字符串,作為緩存中的key
    String requestKey = createKey(request);

    // 第二個(gè)分支:從緩存中獲取
    // 如果設(shè)置了緩存(通過(guò)memoryPolicy方法設(shè)置),先試圖從緩存獲取,獲取成功直接返回
    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會(huì)根據(jù)RequestCreator的各個(gè)設(shè)置項(xiàng)生成一個(gè)request,然后通過(guò)createKey生成一個(gè)key值:

private Request createRequest(long started) {
    int id = nextId.getAndIncrement();
    // data.build構(gòu)造者模式
    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());
    }
    // 如果設(shè)置了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的實(shí)現(xiàn)可以看出,同一個(gè)來(lái)源的圖片,如果加載參數(shù)不同,會(huì)生成不同的key,并分別存儲(chǔ)到緩存中。接下來(lái)判斷是否設(shè)置了內(nèi)存緩存,如果設(shè)置的話通過(guò)picasso.quickMemoryCacheCheck根據(jù)key查找緩存內(nèi)容,找到的話返回這個(gè)bitmap,并設(shè)置給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類(lèi)具體是怎樣實(shí)現(xiàn)的:

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是一個(gè)接口類(lèi),規(guī)范了一系列對(duì)緩存的操作接口,包括get/set/size/clear等,還包含一個(gè)空實(shí)現(xiàn)。Picasso提供了一個(gè)實(shí)現(xiàn)了Cache接口的類(lèi)LruCache,用戶也可以提供自己的實(shí)現(xiàn)。

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遍歷輸出的順序跟元素插入的順序相同,所以緩存的換出機(jī)制是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通過(guò)一個(gè)LinkedHashMap來(lái)存儲(chǔ)圖片鍵值對(duì),LinkedHashMap結(jié)合了鏈表的FIFO特性以及HashMap的鍵值對(duì)存取特性,通過(guò)iterator遍歷的時(shí)候保證先加入的先遍歷到,當(dāng)緩存的大小達(dá)到設(shè)定值的時(shí)候,通過(guò)trimToSize函數(shù)進(jìn)行緩存的換出,借助LinkedHashMap實(shí)現(xiàn)FIFO的換出策略。同時(shí)注意由于多個(gè)線程可以同時(shí)存取緩存,需要進(jìn)行線程同步機(jī)制,這里是通過(guò)synchronized加鎖實(shí)現(xiàn)的。

如果緩存沒(méi)有命中,進(jìn)入into函數(shù)第三個(gè)分支,通過(guò)網(wǎng)絡(luò)或文件系統(tǒng)加載。

    // 第三個(gè)分支:從網(wǎng)絡(luò)或文件系統(tǒng)加載
    // 如果從緩存獲取失敗,則生成一個(gè)Action來(lái)加載該圖片。
    // 一個(gè)Action包含了complete/error/cancel等回調(diào)函數(shù)
    // 對(duì)應(yīng)了圖片加載成功,失敗,取消加載的操作
    Action action =
        new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
            errorDrawable, requestKey, tag, callback, noFade);

    // 通過(guò)picasso對(duì)象將該action加入執(zhí)行隊(duì)列,里面的任務(wù)通過(guò)ThreadPoolExecutor線程池執(zhí)行
    picasso.enqueueAndSubmit(action);

這里一次圖片加載的操作是通過(guò)一個(gè)Action來(lái)表示的,Action是一個(gè)接口類(lèi),提供了跟一次圖片加載相關(guān)的操作,比如請(qǐng)求的Request,網(wǎng)絡(luò)緩存策略,內(nèi)存緩存策略,加載成功的回調(diào)函數(shù),失敗的回調(diào),取消的回調(diào)等。

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的實(shí)現(xiàn),包括ImageViewAction(圖片加載并展示到ImageView),NotificationAction(圖片加載并展示到Notification),GetAction(圖片同步加載不展示),F(xiàn)etchAction(圖片異步加載并設(shè)置回調(diào)函數(shù))等,下面給出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;
        }
    }
}

構(gòu)造完Action通過(guò)picasso對(duì)象加入線程池執(zhí)行:

    // 通過(guò)picasso對(duì)象將該action加入執(zhí)行隊(duì)列,里面的任務(wù)通過(guò)ThreadPoolExecutor線程池執(zhí)行
    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調(diào)用Dispatcher類(lèi)進(jìn)行消息的分發(fā):

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提供對(duì)各種動(dòng)作的響應(yīng),包括提交一個(gè)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);
            }
          });
      }
    }
  }

我們看一下提交一個(gè)Action最終是怎樣得到執(zhí)行的:

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;
    }
    // 根據(jù)每個(gè)Action創(chuàng)建一個(gè)Hunter對(duì)象,并通過(guò)ExecutorService提交到線程池執(zhí)行
    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函數(shù)會(huì)根據(jù)每個(gè)Action創(chuàng)建一個(gè)BitmapHunter對(duì)象,并通過(guò)ExecutorService提交到線程池執(zhí)行。BitmapHunter是一個(gè)多線程類(lèi),提供了加載圖片的操作:

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()函數(shù)的實(shí)現(xiàn):

Bitmap hunt() throws IOException {
    Bitmap bitmap = null;

    // 再次嘗試從內(nèi)存緩存獲取,之前沒(méi)再內(nèi)存緩存中,說(shuō)不定這時(shí)候已經(jīng)在了
    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;
    // 通過(guò)requestHandler.load進(jìn)行加載
    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);
      // 如果設(shè)置了對(duì)bitmap的transform函數(shù),執(zhí)行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;
  }

再次嘗試從內(nèi)存緩存獲取,之前沒(méi)再內(nèi)存緩存中,說(shuō)不定這時(shí)候已經(jīng)在了。如果獲取不到,調(diào)用RequestHandler的load函數(shù)進(jìn)行真正的加載操作。

RequestHandler是個(gè)虛基類(lèi),提供了統(tǒng)一的加載接口:

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等都實(shí)現(xiàn)了RequestHandler基類(lèi),分別提供了網(wǎng)絡(luò)加載,聯(lián)系人圖片加載,Asset資源加載,文件加載,Resource資源圖片加載等不同的加載方式。

這樣,就完成了Picasso加載圖片的整個(gè)流程分析。代碼量適中,結(jié)構(gòu)也比較清晰,適合閱讀學(xué)習(xí)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,324評(píng)論 25 708
  • ¥開(kāi)啟¥ 【iAPP實(shí)現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開(kāi)一個(gè)線程,因...
    小菜c閱讀 7,384評(píng)論 0 17
  • 前一篇文章講了Picasso的詳細(xì)用法,Picasso 是一個(gè)強(qiáng)大的圖片加載緩存框架,一個(gè)非常優(yōu)秀的開(kāi)源庫(kù),學(xué)習(xí)一...
    依然范特稀西閱讀 4,749評(píng)論 13 24
  • 很多時(shí)候,我為了自己而撒謊,這是一件平常不過(guò)的事,只是沒(méi)有想到那個(gè)人,用生命讓我后悔了。 01 凌晨三點(diǎn)四十七分,...
    小理愛(ài)可樂(lè)閱讀 451評(píng)論 5 0
  • 活泉追風(fēng)酒搽劑,本藥酒由幾十位名貴中藥精制而成,主治《頸椎病、肩周炎、頸肩綜合癥、肱骨外上踝炎、網(wǎng)球肘.腕關(guān)節(jié)綜合...
    以斯帖LIQIN獨(dú)家秘方治奇病閱讀 447評(píng)論 1 2

友情鏈接更多精彩內(nèi)容