Picasso源代分析

我每周會寫一篇源代碼分析的文章,以后也可能會有其他主題.
如果你喜歡我寫的文章的話,歡迎關注我的新浪微博@達達達達sky
地址: http://weibo.com/u/2030683111
每周我會第一時間在微博分享我寫的文章,也會積極轉發更多有用的知識給大家.謝謝關注_,說不定什么時候會有福利哈.


1.簡介

Picasso是Square公司開源的一個Android平臺上的圖片加載框架,也是大名鼎鼎的JakeWharton的代表作品之一.對于圖片加載和緩存框架,優秀的開源作品有不少。比如:Android-Universal-Image-Loader,Glide,fresco等等.我自己有在項目中使用過的有Picasso,U-I-L,Glide.對于一般的應用上面這些圖片加載和緩存框架都是能滿足使用的,Trinea有一篇關于這些框架的對比文章Android 三大圖片緩存原理、特性對比.有興趣了解的可以去看看,本文我們主要講Picasso的使用方法和源碼分析.

2.使用方法

//加載一張圖片
Picasso.with(this).load("url").placeholder(R.mipmap.ic_default).into(imageView);

//加載一張圖片并設置一個回調接口
Picasso.with(this).load("url").placeholder(R.mipmap.ic_default).into(imageView, new Callback() {
    @Override
    public void onSuccess() {

    }

    @Override
    public void onError() {

    }
});

//預加載一張圖片
Picasso.with(this).load("url").fetch();

//同步加載一張圖片,注意只能在子線程中調用并且Bitmap不會被緩存到內存里.
new Thread() {
    @Override
    public void run() {
        try {
            final Bitmap bitmap = Picasso.with(getApplicationContext()).load("url").get();
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    imageView.setImageBitmap(bitmap);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}.start();

//加載一張圖片并自適應imageView的大小,如果imageView設置了wrap_content,會顯示不出來.直到該ImageView的
//LayoutParams被設置而且調用了該View的ViewTreeObserver.OnPreDrawListener回調接口后才會顯示.
Picasso.with(this).load("url").priority(Picasso.Priority.HIGH).fit().into(imageView);

//加載一張圖片并按照指定尺寸以centerCrop()的形式縮放.
Picasso.with(this).load("url").resize(200,200).centerCrop().into(imageView);

//加載一張圖片并按照指定尺寸以centerInside()的形式縮放.并設置加載的優先級為高.注意centerInside()或centerCrop()
//只能同時使用一種,而且必須指定resize()或者resizeDimen();
Picasso.with(this).load("url").resize(400,400).centerInside().priority(Picasso.Priority.HIGH).into(imageView);

//加載一張圖片旋轉并且添加一個Transformation,可以對圖片進行各種變化處理,例如圓形頭像.
Picasso.with(this).load("url").rotate(10).transform(new Transformation() {
    @Override
    public Bitmap transform(Bitmap source) {
        //處理Bitmap
        return null;
    }

    @Override
    public String key() {
        return null;
    }
}).into(imageView);

//加載一張圖片并設置tag,可以通過tag來暫定或者繼續加載,可以用于當ListView滾動是暫定加載.停止滾動恢復加載.
Picasso.with(this).load("url").tag(mContext).into(imageView);
Picasso.with(this).pauseTag(mContext);
Picasso.with(this).resumeTag(mContxt);
        

上面我們介紹了Picasso的大部分常用的使用方法.此外Picasso內部還具有監控功能.可以檢測內存數據,緩存命中率等等.而且還會根據網絡變化優化并發線程.下面我們就來進行Picasso的源碼分析。這里說明一下,Picasso的源碼分析目前在網絡上已經有幾篇比較好的分析文章,我在分析的時候也借鑒了不少,分別是RowandJJ的Picasso源碼學習閉門造車的Picasso源碼分析系列.在這里注明,下文章有部分圖是引用自這兩個地方的.引用就不做具體標注了.

3.類關系圖

Picasso-classes-relation.png

從類圖上我們可以看出Picasso的核心類主要包括:Picasso,RequestCreator,Action,Dispatcher,Request,RequestHandler,BitmapHunter等等.一張圖片加載可以分為以下幾步:

創建->入隊->執行->解碼->變換->批處理->完成->分發->顯示(可選)

下面就讓我們來通過Picasso的調用流程來具體分析它的具體實現.

4.源碼分析

Picasso.with()方法的實現

按照我們的慣例,我們從Picasso的調用流程開始分析,我們就從加載一張圖片開始看起:

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

讓我們先來看看Picasso.with()做了什么:

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

維護一個Picasso的單例,如果還未實例化就通過new Builder(context).build()創建一個singleton并返回,我們繼續看Builder類的實現:

      public static class Builder {
    
        public Builder(Context context) {
          if (context == null) {
            throw new IllegalArgumentException("Context must not be null.");
          }
          this.context = context.getApplicationContext();
        }
    
        /** Create the {@link Picasso} instance. */
        public Picasso build() {
          Context context = this.context;
    
          if (downloader == null) {
            //創建默認下載器
            downloader = Utils.createDefaultDownloader(context);
          }
          if (cache == null) {
            //創建Lru內存緩存
            cache = new LruCache(context);
          }
          if (service == null) {
            //創建線程池,默認有3個執行線程,會根據網絡狀況自動切換線程數
            service = new PicassoExecutorService();
          }
          if (transformer == null) {
            //創建默認的transformer,并無實際作用
            transformer = RequestTransformer.IDENTITY;
          }
          //創建stats用于統計緩存,以及緩存命中率,下載數量等等
          Stats stats = new Stats(cache);
          //創建dispatcher對象用于任務的調度
          Dispatcher dispatcher = new Dispatcher(context, service, HANDLER, downloader, cache, stats);
    
          return new Picasso(context, dispatcher, cache, listener, transformer, requestHandlers, stats,
              defaultBitmapConfig, indicatorsEnabled, loggingEnabled);
        }
      }

上面的代碼里省去了部分配置的方法,當我們使用Picasso默認配置的時候(當然也可以自定義),最后會調用build()方法并配置好我們需要的各種對象,最后實例化一個Picasso對象并返回。最后在Picasso的構造方法里除了對這些對象的賦值以及創建一些新的對象,例如清理線程等等.最重要的是初始化了requestHandlers,下面是代碼片段:

    List<RequestHandler> allRequestHandlers =
        new ArrayList<RequestHandler>(builtInHandlers + extraCount);
    
    // ResourceRequestHandler needs to be the first in the list to avoid
    // forcing other RequestHandlers to perform null checks on request.uri
    // to cover the (request.resourceId != 0) case.
    allRequestHandlers.add(new ResourceRequestHandler(context));
    if (extraRequestHandlers != null) {
      allRequestHandlers.addAll(extraRequestHandlers);
    }
    allRequestHandlers.add(new ContactsPhotoRequestHandler(context));
    allRequestHandlers.add(new MediaStoreRequestHandler(context));
    allRequestHandlers.add(new ContentStreamRequestHandler(context));
    allRequestHandlers.add(new AssetRequestHandler(context));
    allRequestHandlers.add(new FileRequestHandler(context));
    allRequestHandlers.add(new NetworkRequestHandler(dispatcher.downloader, stats));
    requestHandlers = Collections.unmodifiableList(allRequestHandlers);

可以看到除了添加我們可以自定義的extraRequestHandlers,另外添加了7個RequestHandler分別用來處理加載不同來源的資源,可能是Resource里的,也可能是File也可能是來源于網絡的資源.這里使用了一個ArrayList來存放這些RequestHandler現在先不用了解這么做是為什么,下面我們會分析,到這我們就了解了Picasso.with()做了什么,接下來我們去看看load()方法.

load(),centerInside(),等方法的實現

Picassoload()方法里我們可以傳入String,Uri或者File對象,但是其最終都是返回一個RequestCreator對象,如下所示:

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

再來看看RequestCreator的構造方法:

  RequestCreator(Picasso picasso, Uri uri, int resourceId) {
    if (picasso.shutdown) {
      throw new IllegalStateException(
          "Picasso instance already shut down. Cannot submit new requests.");
    }
    this.picasso = picasso;
    this.data = new Request.Builder(uri, resourceId, picasso.defaultBitmapConfig);
  }

首先是持有一個Picasso的對象,然后構建一個RequestBuilder對象,將我們需要加載的圖片的信息都保存在data里,在我們通過.centerCrop()或者.transform()等等方法的時候實際上也就是改變data內的對應的變量標識,再到處理的階段根據這些參數來進行對應的操作,所以在我們調用into()方法之前,所有的操作都是在設定我們需要處理的參數,真正的操作都是有into()方法引起的。

into()方法的實現

從上文中我們知道在我們調用了load()方法之后會返回一個RequestCreator對象,所以.into(imageView)方法必然是在RequestCreator里:


  public void into(ImageView target) {
    //傳入空的callback
    into(target, null);
  }

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

    if (target == null) {
      throw new IllegalArgumentException("Target must not be null.");
    }
    //如果沒有設置需要加載的uri,或者resourceId
    if (!data.hasImage()) {
      picasso.cancelRequest(target);
      //如果設置占位圖片,直接加載并返回
      if (setPlaceholder) {
        setPlaceholder(target, getPlaceholderDrawable());
      }
      return;
    }
    //如果是延時加載,也就是選擇了fit()模式
    if (deferred) {
      //fit()模式是適應target的寬高加載,所以并不能手動設置resize,如果設置就拋出異常
      if (data.hasSize()) {
        throw new IllegalStateException("Fit cannot be used with resize.");
      }
      int width = target.getWidth();
      int height = target.getHeight();
      //如果目標ImageView的寬或高現在為0
      if (width == 0 || height == 0) {
        //先設置占位符
        if (setPlaceholder) {
          setPlaceholder(target, getPlaceholderDrawable());
        }
        //監聽ImageView的ViewTreeObserver.OnPreDrawListener接口,一旦ImageView
        //的寬高被賦值,就按照ImageView的寬高繼續加載.
        picasso.defer(target, new DeferredRequestCreator(this, target, callback));
        return;
      }
      //如果ImageView有寬高就設置設置
      data.resize(width, height);
    }

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

    //根據memoryPolicy來決定是否可以從內存里讀取
    if (shouldReadFromMemoryCache(memoryPolicy)) {
      //通過LruCache來讀取內存里的緩存圖片
      Bitmap bitmap = picasso.quickMemoryCacheCheck(requestKey);
      //如果讀取到
      if (bitmap != null) {
        //取消target的request
        picasso.cancelRequest(target);
        //設置圖片
        setBitmap(target, picasso.context, bitmap, MEMORY, noFade, picasso.indicatorsEnabled);
        if (picasso.loggingEnabled) {
          log(OWNER_MAIN, VERB_COMPLETED, request.plainId(), "from " + MEMORY);
        }
        //如果設置了回調接口就回調接口的方法.
        if (callback != null) {
          callback.onSuccess();
        }
        return;
      }
    }
    //如果緩存里沒讀到,先根據是否設置了占位圖并設置占位
    if (setPlaceholder) {
      setPlaceholder(target, getPlaceholderDrawable());
    }
    //構建一個Action對象,由于我們是往ImageView里加載圖片,所以這里創建的是一個ImageViewAction對象.
    Action action =
        new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
            errorDrawable, requestKey, tag, callback, noFade);

    //將Action對象入列提交
    picasso.enqueueAndSubmit(action);
  }

整個流程看下來應該是比較清晰的,最后是創建了一個ImageViewAction對象并通過picasso提交,這里簡要說明一下ImageViewAction,實際上Picasso會根據我們調用的不同方式來實例化不同的Action對象,當我們需要往ImageView里加載圖片的時候會創建ImageViewAction對象,如果是往實現了Target接口的對象里加載圖片是則會創建TargetAction對象,這些Action類的實現類不僅保存了這次加載需要的所有信息,還提供了加載完成后的回調方法.也是由子類實現并用來完成不同的調用的。然后讓我們繼續去看picasso.enqueueAndSubmit(action)方法:

  void enqueueAndSubmit(Action action) {
    Object target = action.getTarget();
    //取消這個target已經有的action.
    if (target != null && targetToAction.get(target) != action) {
      // This will also check we are on the main thread.
      cancelExistingRequest(target);
      targetToAction.put(target, action);
    }
    //提交action
    submit(action);
  }
  //調用dispatcher來派發action
  void submit(Action action) {
    dispatcher.dispatchSubmit(action);
  }

很簡單,最后是轉到了dispatcher類來處理,那我們就來看看dispatcher.dispatchSubmit(action)方法:

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

看到通過一個handler對象發送了一個REQUEST_SUBMIT的消息,那么這個handler是存在與哪個線程的呢?

  Dispatcher(Context context, ExecutorService service, Handler mainThreadHandler,
      Downloader downloader, Cache cache, Stats stats) {
    this.dispatcherThread = new DispatcherThread();
    this.dispatcherThread.start();    
    this.handler = new DispatcherHandler(dispatcherThread.getLooper(), this);
    this.mainThreadHandler = mainThreadHandler;
  }
  
    static class DispatcherThread extends HandlerThread {
    DispatcherThread() {
      super(Utils.THREAD_PREFIX + DISPATCHER_THREAD_NAME, THREAD_PRIORITY_BACKGROUND);
    }
  }

上面是Dispatcher的構造方法(省略了部分代碼),可以看到先是創建了一個HandlerThread對象,然后創建了一個DispatcherHandler對象,這個handler就是剛剛用來發送REQUEST_SUBMIT消息的handler,這里我們就明白了原來是通過Dispatcher類里的一個子線程里的handler不斷的派發我們的消息,這里是用來派發我們的REQUEST_SUBMIT消息,而且最終是調用了 dispatcher.performSubmit(action);方法:

  void performSubmit(Action action) {
    performSubmit(action, true);
  }

  void performSubmit(Action action, boolean dismissFailed) {
    //是否該tag的請求被暫停
    if (pausedTags.contains(action.getTag())) {
      pausedActions.put(action.getTarget(), action);
      if (action.getPicasso().loggingEnabled) {
        log(OWNER_DISPATCHER, VERB_PAUSED, action.request.logId(),
            "because tag '" + action.getTag() + "' is paused");
      }
      return;
    }
    //通過action的key來在hunterMap查找是否有相同的hunter,這個key里保存的是我們
    //的uri或者resourceId和一些參數,如果都是一樣就將這些action合并到一個
    //BitmapHunter里去.
    BitmapHunter hunter = hunterMap.get(action.getKey());
    if (hunter != null) {
      hunter.attach(action);
      return;
    }

    if (service.isShutdown()) {
      if (action.getPicasso().loggingEnabled) {
        log(OWNER_DISPATCHER, VERB_IGNORED, action.request.logId(), "because shut down");
      }
      return;
    }

    //創建BitmapHunter對象
    hunter = forRequest(action.getPicasso(), this, cache, stats, action);
    //通過service執行hunter并返回一個future對象
    hunter.future = service.submit(hunter);
    //將hunter添加到hunterMap中
    hunterMap.put(action.getKey(), hunter);
    if (dismissFailed) {
      failedActions.remove(action.getTarget());
    }

    if (action.getPicasso().loggingEnabled) {
      log(OWNER_DISPATCHER, VERB_ENQUEUED, action.request.logId());
    }
  }

注釋很詳細,這里我們再分析一下forRequest()是如何實現的:

  static BitmapHunter forRequest(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats,
      Action action) {
    Request request = action.getRequest();
    List<RequestHandler> requestHandlers = picasso.getRequestHandlers();

    //從requestHandlers中檢測哪個RequestHandler可以處理這個request,如果找到就創建
    //BitmapHunter并返回.
    for (int i = 0, count = requestHandlers.size(); i < count; i++) {
      RequestHandler requestHandler = requestHandlers.get(i);
      if (requestHandler.canHandleRequest(request)) {
        return new BitmapHunter(picasso, dispatcher, cache, stats, action, requestHandler);
      }
    }

    return new BitmapHunter(picasso, dispatcher, cache, stats, action, ERRORING_HANDLER);
  }

這里就體現出來了責任鏈模式,通過依次調用requestHandlersRequestHandlercanHandleRequest()方法來確定這個request能被哪個RequestHandler執行,找到對應的RequestHandler后就創建BitmapHunter對象并返回.再回到performSubmit()方法里,通過service.submit(hunter);執行了hunter,hunter實現了Runnable接口,所以run()方法就會被執行,所以我們繼續看看BitmapHunterrun()方法的實現:

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

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

      //調用hunt()方法并返回Bitmap類型的result對象.
      result = hunt();

      //如果為空,調用dispatcher發送失敗的消息,
      //如果不為空則發送完成的消息
      if (result == null) {
        dispatcher.dispatchFailed(this);
      } else {
        dispatcher.dispatchComplete(this);
      }
    //通過不同的異常來進行對應的處理
    } catch (Downloader.ResponseException e) {
      if (!e.localCacheOnly || e.responseCode != 504) {
        exception = e;
      }
      dispatcher.dispatchFailed(this);
    } catch (NetworkRequestHandler.ContentLengthException e) {
      exception = e;
      dispatcher.dispatchRetry(this);
    } catch (IOException e) {
      exception = e;
      dispatcher.dispatchRetry(this);
    } catch (OutOfMemoryError e) {
      StringWriter writer = new StringWriter();
      stats.createSnapshot().dump(new PrintWriter(writer));
      exception = new RuntimeException(writer.toString(), e);
      dispatcher.dispatchFailed(this);
    } catch (Exception e) {
      exception = e;
      dispatcher.dispatchFailed(this);
    } finally {
      Thread.currentThread().setName(Utils.THREAD_IDLE_NAME);
    }
  }

  Bitmap hunt() throws IOException {
    Bitmap bitmap = null;
    //是否可以從內存中讀取
    if (shouldReadFromMemoryCache(memoryPolicy)) {
      bitmap = cache.get(key);
      if (bitmap != null) {
        //統計緩存命中率
        stats.dispatchCacheHit();
        loadedFrom = MEMORY;
        if (picasso.loggingEnabled) {
          log(OWNER_HUNTER, VERB_DECODED, data.logId(), "from cache");
        }
        return bitmap;
      }
    }

    //如果未設置networkPolicy并且retryCount為0,則將networkPolicy設置為
    //NetworkPolicy.OFFLINE
    data.networkPolicy = retryCount == 0 ? NetworkPolicy.OFFLINE.index : networkPolicy;
    //通過對應的requestHandler來獲取result
    RequestHandler.Result result = requestHandler.load(data, networkPolicy);
    if (result != null) {
      loadedFrom = result.getLoadedFrom();
      exifOrientation = result.getExifOrientation();
      bitmap = result.getBitmap();

      // If there was no Bitmap then we need to decode it from the stream.
      if (bitmap == null) {
        InputStream is = result.getStream();
        try {
          bitmap = decodeStream(is, data);
        } finally {
          Utils.closeQuietly(is);
        }
      }
    }

    if (bitmap != null) {
      if (picasso.loggingEnabled) {
        log(OWNER_HUNTER, VERB_DECODED, data.logId());
      }
      stats.dispatchBitmapDecoded(bitmap);
      //處理Transformation
      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;
  }

run()方法里調用了hunt()方法來獲取result然后通知了dispatcher來處理結果,并在try-catch里通知dispatcher來處理相應的異常,在hunt()方法里通過前面指定的requestHandler來獲取相應的result,我們是從網絡加載圖片,自然是調用NetworkRequestHandlerload()方法來處理我們的request,這里我們就不再分析NetworkRequestHandler具體的細節.獲取到result之后就獲得我們的bitmap然后檢測是否需要Transformation,這里使用了一個全局鎖DECODE_LOCK來保證同一個時刻僅僅有一個圖片正在處理。我們假設我們的請求被正確處理了,這樣我們拿到我們的result然后調用了dispatcher.dispatchComplete(this);最終也是通過handler調用了dispatcher.performComplete()方法:

  void performComplete(BitmapHunter hunter) {
    //是否可以放入內存緩存里
    if (shouldWriteToMemoryCache(hunter.getMemoryPolicy())) {
      cache.set(hunter.getKey(), hunter.getResult());
    }
    //從hunterMap移除
    hunterMap.remove(hunter.getKey());
    //處理hunter
    batch(hunter);
    if (hunter.getPicasso().loggingEnabled) {
      log(OWNER_DISPATCHER, VERB_BATCHED, getLogIdsForHunter(hunter), "for completion");
    }
  }
  
  private void batch(BitmapHunter hunter) {
    if (hunter.isCancelled()) {
      return;
    }
    batch.add(hunter);
    if (!handler.hasMessages(HUNTER_DELAY_NEXT_BATCH)) {
      handler.sendEmptyMessageDelayed(HUNTER_DELAY_NEXT_BATCH, BATCH_DELAY);
    }
  }
  
  void performBatchComplete() {
    List<BitmapHunter> copy = new ArrayList<BitmapHunter>(batch);
    batch.clear();
    mainThreadHandler.sendMessage(mainThreadHandler.obtainMessage(HUNTER_BATCH_COMPLETE, copy));
    logBatch(copy);
  }

首先是添加到內存緩存中去,然后在發送一個HUNTER_DELAY_NEXT_BATCH消息,實際上這個消息最后會出發performBatchComplete()方法,performBatchComplete()里則是通過mainThreadHandlerBitmapHunterList發送到主線程處理,所以我們去看看mainThreadHandlerhandleMessage()方法:

  static final Handler HANDLER = new Handler(Looper.getMainLooper()) {
    @Override public void handleMessage(Message msg) {
      switch (msg.what) {
        case HUNTER_BATCH_COMPLETE: {
          @SuppressWarnings("unchecked") List<BitmapHunter> batch = (List<BitmapHunter>) msg.obj;
          //noinspection ForLoopReplaceableByForEach
          for (int i = 0, n = batch.size(); i < n; i++) {
            BitmapHunter hunter = batch.get(i);
            hunter.picasso.complete(hunter);
          }
          break;
        }
        default:
          throw new AssertionError("Unknown handler message received: " + msg.what);
      }
    }
  };

很簡單,就是依次調用picasso.complete(hunter)方法:

 void complete(BitmapHunter hunter) {
    //獲取單個Action
    Action single = hunter.getAction();
    //獲取被添加進來的Action
    List<Action> joined = hunter.getActions();

    //是否有合并的Action
    boolean hasMultiple = joined != null && !joined.isEmpty();
    //是否需要派發
    boolean shouldDeliver = single != null || hasMultiple;

    if (!shouldDeliver) {
      return;
    }

    Uri uri = hunter.getData().uri;
    Exception exception = hunter.getException();
    Bitmap result = hunter.getResult();
    LoadedFrom from = hunter.getLoadedFrom();

    //派發Action
    if (single != null) {
      deliverAction(result, from, single);
    }

    //派發合并的Action
    if (hasMultiple) {
      //noinspection ForLoopReplaceableByForEach
      for (int i = 0, n = joined.size(); i < n; i++) {
        Action join = joined.get(i);
        deliverAction(result, from, join);
      }
    }

    if (listener != null && exception != null) {
      listener.onImageLoadFailed(this, uri, exception);
    }
  }
  
 private void deliverAction(Bitmap result, LoadedFrom from, Action action) {
    if (action.isCancelled()) {
      return;
    }
    if (!action.willReplay()) {
      targetToAction.remove(action.getTarget());
    }
    if (result != null) {
      if (from == null) {
        throw new AssertionError("LoadedFrom cannot be null.");
      }
      //回調action的complete()方法
      action.complete(result, from);
      if (loggingEnabled) {
        log(OWNER_MAIN, VERB_COMPLETED, action.request.logId(), "from " + from);
      }
    } else {
      //失敗則回調error()方法
      action.error();
      if (loggingEnabled) {
        log(OWNER_MAIN, VERB_ERRORED, action.request.logId());
      }
    }
  }

可以看出最終是回調了actioncomplete()方法,從前文知道我們這里是ImageViewAction,所以我們去看看ImageViewActioncomplete()的實現:

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

    //得到target也就是ImageView
    ImageView target = this.target.get();
    if (target == null) {
      return;
    }

    Context context = picasso.context;
    boolean indicatorsEnabled = picasso.indicatorsEnabled;
    //通過PicassoDrawable來將bitmap設置到ImageView上
    PicassoDrawable.setBitmap(target, context, result, from, noFade, indicatorsEnabled);

    //回調callback接口
    if (callback != null) {
      callback.onSuccess();
    }
  }

很顯然通過了PicassoDrawable.setBitmap()將我們的Bitmap設置到了我們的ImageView上,最后并回調callback接口,這里為什么會使用PicassoDrawabl來設置Bitmap呢?使用過Picasso的都知道,Picasso自帶漸變的加載動畫,所以這里就是處理漸變動畫的地方,由于篇幅原因我們就不做具體分析了,感興趣的同學可以自行研究,所以到這里我們的整個Picasso的調用流程的源碼分析就結束了.

5.設計模式

建造者模式

建造者模式是指:將一個復雜對象的構建與它的表示分離,使得同樣的構建過程可以創建不同的表示。建造者模式應該是我們都比較熟悉的一種模式,在創建AlertDialog的時候通過配置不同的參數就可以展示不同的AlertDialog,這也正是建造者模式的用途,通過不同的參數配置或者不同的執行順序來構建不同的對象,在Picasso里當構建RequestCreator的時候正是使用了這種設計模式,我們通過可選的配置比如centerInside(),placeholder()等等來分別達到不同的使用方式,在這種使用場景下使用建造者模式是非常合適的.

責任鏈模式

責任鏈模式是指:一個請求沿著一條“鏈”傳遞,直到該“鏈”上的某個處理者處理它為止。當我們有一個請求可以被多個處理者處理或處理者未明確指定時。可以選擇使用責任鏈模式,在Picasso里當我們通過BitmapHunterforRequest()方法構建一個BitmapHunter對象時,需要為Request指定一個對應的RequestHandler來進行處理Request.這里就使用了責任鏈模式,依次調用requestHandler.canHandleRequest(request)方法來判斷是否該RequestHandler能處理該Request如果可以就構建一個RequestHandler對象返回.這里就是典型的責任鏈思想的體現。

6.個人評價

Picasso是我最早接觸Android時第一個使用的圖片加載庫,當時也了解過U-I-L,但是最終選擇使用了Picasso因為對于當時的我來說Picasso使用起來足夠簡單,簡單到我根本不需要任何配置一行代碼就可以搞定圖片加載,所以對于初學者Picasso可以算得上最易使用的圖片加載緩存庫了,而且分析完源代碼發現Picasso實現的feature并不算少,對于一個標準的圖片庫功能也可謂是應有竟有,雖然比GlideFresco是少一些功能或者性能,但是作為出現時間比較早的圖片加載庫還是值得推薦學習和使用的。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,527評論 6 544
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,687評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,640評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,957評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,682評論 6 413
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 56,011評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,009評論 3 449
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,183評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,714評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,435評論 3 359
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,665評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,148評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,838評論 3 350
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,251評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,588評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,379評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,627評論 2 380

推薦閱讀更多精彩內容