圖片加載庫-Picasso源碼分析

概述

在Android開發(fā)界,大家都知到square出品必屬精品,圖片加載庫Picasso自然也是。本文就從源碼角度,詳細分析下Picasso。

基本使用

下面的代碼為一次簡單的網(wǎng)絡(luò)加載圖片

     Picasso.with(getApplicationContext())
               .load("http://www.qlnh.com/uploads/image/20160714/20160714114238_6824.jpg")
                .placeholder(holderDrawable)
                .error(errorDrawable)
                .into(imageView);

可以看到,整個調(diào)用流程結(jié)構(gòu)非常清晰,鏈式方法看起來也讓人賞心悅目。當(dāng)然這只是一個基本的網(wǎng)絡(luò)加載圖片例子,你也可以配置很多其他參數(shù),如圖片裁減,旋轉(zhuǎn)等等。

下面詳細分析Picasso的核心類及加載流程

Picasso的初始化

Picasso庫采用了門面設(shè)計模式,調(diào)用都是從Picasso類開始的,而Picasso內(nèi)部組件的初始化也是在Picasso類中執(zhí)行的。如果不需要自定義Picasso,直接使用單例模式Picasso with(Context context)獲取Picasso實例就可以了,而如果需要自定義Picasso類則可以在調(diào)用Picasso with(Context context)之前先通過setSingletonInstance(Picasso picasso)來設(shè)置Picasso
下面來看看Picasso有那些可以自定義的組件

public static class Builder {
    private final Context context;
    private Downloader downloader;  //下載器
    private ExecutorService service;    //網(wǎng)絡(luò)任務(wù)線程池
    private Cache cache;       //內(nèi)存緩存
    private Listener listener;    //onImageLoadFailed 監(jiān)聽
    private RequestTransformer transformer;  //Request提交前的預(yù)留hook接口
    private List<RequestHandler> requestHandlers;   //請求處理者集合
    private Bitmap.Config defaultBitmapConfig;  //默認bitmap設(shè)置信息

    private boolean indicatorsEnabled;   //是否debug 信息提示顯示
    private boolean loggingEnabled;  //是否打印log
...

如果沒有自定義,Picasso類就會使用默認配置。

 public Picasso build() {
      Context context = this.context;

      if (downloader == null) {
        downloader = Utils.createDefaultDownloader(context);
      }
      if (cache == null) {
        cache = new LruCache(context);
      }
      if (service == null) {
        service = new PicassoExecutorService();
      }
      if (transformer == null) {
        transformer = RequestTransformer.IDENTITY;
      }

      Stats stats = new Stats(cache);

      Dispatcher dispatcher = new Dispatcher(context, service, HANDLER, downloader, cache, stats);

      return new Picasso(context, dispatcher, cache, listener, transformer, requestHandlers, stats,
          defaultBitmapConfig, indicatorsEnabled, loggingEnabled);
    }

下面來看看這些組件的默認配置:

  1. downloader
    downloader 類是對網(wǎng)絡(luò)實現(xiàn)的抽象接口,有Response load(Uri uri, int networkPolicy),void shutdown();,InputStream getInputStream()等方法。下面的創(chuàng)建默認實現(xiàn)的方法中會反射判斷項目是否依賴okhttp庫,如果有okhttp庫就使用okhttp來實現(xiàn)downloader,否則就采用httpurlconnection來實現(xiàn)。其實在volleyglide 等開源庫都有如此設(shè)計,可以方便切換okhttp或者httpurlconnection作為網(wǎng)絡(luò)請求的默認實現(xiàn)。
static Downloader createDefaultDownloader(Context context) {
    try {
      Class.forName("com.squareup.okhttp.OkHttpClient");
      return OkHttpLoaderCreator.create(context);
    } catch (ClassNotFoundException ignored) {
    }
    return new UrlConnectionDownloader(context);
  }
  1. cache
    cache接口作為內(nèi)存緩存的抽象接口有以下方法
/** 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);

默認的實現(xiàn)為LruCache,既當(dāng)內(nèi)存達到最大值時移除最早的緩存

  1. service
    默認實現(xiàn)為PicassoExecutorService
private static final int DEFAULT_THREAD_COUNT = 3;
PicassoExecutorService() {
    super(DEFAULT_THREAD_COUNT, DEFAULT_THREAD_COUNT, 0, TimeUnit.MILLISECONDS,
        new PriorityBlockingQueue<Runnable>(), new Utils.PicassoThreadFactory());
  }

這個也好理解,就是一個線程數(shù)為3的固定線程池,注意這個線程池的的等待隊列為PriorityBlockingQueue。另一方面,Picasso中注冊了,接受了網(wǎng)絡(luò)信號變化的廣播接收者,當(dāng)網(wǎng)絡(luò)切換時會根據(jù)網(wǎng)絡(luò)類型動態(tài)變化線程池的線程數(shù)。

  1. Dispatcher
    DispatcherPicasso非常重要的一個類,所有任務(wù)的執(zhí)行都要經(jīng)它之手。其沒有對使用者提供自定義選項。下面是一些dispatcher的方法,基本都是將任務(wù)發(fā)送到其內(nèi)部的一個handler處理,這個handler是運行的handlerthread的專門來處理任務(wù)派發(fā)的。
...
  void dispatchSubmit(Action action) {
    handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));
  }

  void dispatchCancel(Action action) {
    handler.sendMessage(handler.obtainMessage(REQUEST_CANCEL, action));
  }

  void dispatchResumeTag(Object tag) {
    handler.sendMessage(handler.obtainMessage(TAG_RESUME, tag));
  }

  void dispatchComplete(BitmapHunter hunter) {
    handler.sendMessage(handler.obtainMessage(HUNTER_COMPLETE, hunter));
  }

  void dispatchRetry(BitmapHunter hunter) {
    handler.sendMessageDelayed(handler.obtainMessage(HUNTER_RETRY, hunter), RETRY_DELAY);
  }

  void dispatchFailed(BitmapHunter hunter) {
    handler.sendMessage(handler.obtainMessage(HUNTER_DECODE_FAILED, hunter));
  }

  void dispatchNetworkStateChange(NetworkInfo info) {
    handler.sendMessage(handler.obtainMessage(NETWORK_STATE_CHANGE, info));
  }
...
  1. transformer &stats
    這兩個組件都是非核心組件,transformer 是給提交request前的一個hook接口,默認是直接返回request
  RequestTransformer IDENTITY = new RequestTransformer() {
      @Override public Request transformRequest(Request request) {
        return request;
      }
    };

而stats 是負責(zé)統(tǒng)計的類,與核心功能無關(guān)。

核心類

下面以一次圖片加載過程的順序來介紹下這些核心類

Request&RequestCreator

Request是封裝圖片請求(包括url,圖片變形參數(shù),請求優(yōu)先級)等的model類,而RequestCreator則是創(chuàng)建Request的輔助類,其是非常重要的一個類。
我們通過Picasso.load()方法會返回一個RequestCreator對象,之后我們可以在RequestCreator上設(shè)置placeholdererror等狀態(tài)的圖片,也可以設(shè)置transform,rotate等參數(shù)。最終通過into()方法,創(chuàng)建request并提交. into()方法有好幾種重載下面以target為imageview的into方法為例來分析一下.

public void into(ImageView target, Callback callback) {
    long started = System.nanoTime();
    checkMain();  //檢查是否主線程,若不是拋出異常

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

    if (!data.hasImage()) {  //檢查是否有設(shè)置url或者resId,若都沒有拋出異常
      picasso.cancelRequest(target);
      if (setPlaceholder) {
        setPlaceholder(target, getPlaceholderDrawable());
      }
      return;
    }

    if (deferred) {//fit()模式
      if (data.hasSize()) { //fit()模式是適應(yīng)target的寬高加載,不能手動設(shè)置resize,如果設(shè)置就拋出異常
        throw new IllegalStateException("Fit cannot be used with resize.");
      }
      int width = target.getWidth();
      int height = target.getHeight();
      if (width == 0 || height == 0) {
        if (setPlaceholder) {
          setPlaceholder(target, getPlaceholderDrawable());
        }
        picasso.defer(target, new DeferredRequestCreator(this, target, callback));
        return;
      }
      data.resize(width, height);
    }
  
    Request request = createRequest(started); //創(chuàng)建Request
    String requestKey = createKey(request);

    if (shouldReadFromMemoryCache(memoryPolicy)) {  //是否從內(nèi)存讀取
      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) {  //設(shè)置placeholder
      setPlaceholder(target, getPlaceholderDrawable());
    }

    Action action =     //創(chuàng)建Action
        new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
            errorDrawable, requestKey, tag, callback, noFade);

    picasso.enqueueAndSubmit(action);  //action入隊
  }

Action

Action是封裝了請求和target及內(nèi)存策略等參數(shù)的類,在上一節(jié)的Requestcreator.into()方法中創(chuàng)建,然后交由Picasso類執(zhí)行(picasso.enqueueAndSubmit(action)),下面來看看這個提交過程都做了什么

//Picasso類中
void enqueueAndSubmit(Action action) {
    Object target = action.getTarget();
    if (target != null && targetToAction.get(target) != action) {//取消target此前的任務(wù)
      // This will also check we are on the main thread.
      cancelExistingRequest(target);  //取消已存在的action
      targetToAction.put(target, action); //添加到target-action map集合
    }
    submit(action); 
  }
void submit(Action action) {
    dispatcher.dispatchSubmit(action); //委托dispatcher執(zhí)行
  }

//Dispatcher類中
 void performSubmit(Action action) {
    performSubmit(action, true);
  }
void performSubmit(Action action, boolean dismissFailed) {
    if (pausedTags.contains(action.getTag())) {
      pausedActions.put(action.getTarget(), action); //如果需要pause則pause
      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已經(jīng)存在,attach
      hunter.attach(action);
      return;
    }

    if (service.isShutdown()) {  //檢查線程池
      if (action.getPicasso().loggingEnabled) {
        log(OWNER_DISPATCHER, VERB_IGNORED, action.request.logId(), "because shut down");
      }
      return;
    }

    hunter = forRequest(action.getPicasso(), this, cache, stats, action);  //創(chuàng)建hunter
    hunter.future = service.submit(hunter);  //向線程池提交hunter
    hunterMap.put(action.getKey(), hunter);
    if (dismissFailed) {
      failedActions.remove(action.getTarget());
    }

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

上面代碼先是判斷了target是否已存在action,如果是則pause之前的target,然后Picasso類把任務(wù)的啟動交給dispatcher來執(zhí)行,dispatcher檢查action對應(yīng)的hunter是否已創(chuàng)建,如果創(chuàng)建則直接將actionattachhunter即可,如果hunter沒有創(chuàng)建則創(chuàng)建hunter并將其提交給線程池執(zhí)行.

BitmapHunter

由上一節(jié)可知一個請求任務(wù)最終的執(zhí)行者就是bitmaphunter,先來看看bitmaphunter的創(chuàng)建:

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

    // Index-based loop to avoid allocating an iterator.
    //noinspection ForLoopReplaceableByForEach
    for (int i = 0, count = requestHandlers.size(); i < count; i++) {
      RequestHandler requestHandler = requestHandlers.get(i);
      if (requestHandler.canHandleRequest(request)) {
        return new BitmapHunter(picasso, dispatcher, cache, stats, action, requestHandler);
      }
    }

    return new BitmapHunter(picasso, dispatcher, cache, stats, action, ERRORING_HANDLER);
  }
 BitmapHunter(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats, Action action,
      RequestHandler requestHandler) {
    this.sequence = SEQUENCE_GENERATOR.incrementAndGet();
    this.picasso = picasso;
    this.dispatcher = dispatcher;
    this.cache = cache;
    this.stats = stats;
    this.action = action;
    this.key = action.getKey();
    this.data = action.getRequest();
    this.priority = action.getPriority();
    this.memoryPolicy = action.getMemoryPolicy();
    this.networkPolicy = action.getNetworkPolicy();
    this.requestHandler = requestHandler;
    this.retryCount = requestHandler.getRetryCount();
  }

bitmaphunter對象的創(chuàng)建是有static 方法forRequest完成的,其主要工作是根據(jù)request尋找到可以處理此requestRequestHandler,這里的尋找過程采用了責(zé)任鏈模式,可以借鑒一下.
Picasso對象的requestHandlers是在Picasso初始化時創(chuàng)建的,其有以下幾種

    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));  //聯(lián)系人頭像
    allRequestHandlers.add(new MediaStoreRequestHandler(context));     //媒體存儲
    allRequestHandlers.add(new ContentStreamRequestHandler(context));   //內(nèi)容提供者
    allRequestHandlers.add(new AssetRequestHandler(context));      //assert讀取
    allRequestHandlers.add(new FileRequestHandler(context));       //文件讀取
    allRequestHandlers.add(new NetworkRequestHandler(dispatcher.downloader, stats));  //網(wǎng)絡(luò)獲取
    requestHandlers = Collections.unmodifiableList(allRequestHandlers);

通過責(zé)任鏈模式我們可以很方便的擴展處理request的handler

再來看看bitmaphunter類的run方法:

 @Override public void run() {
    try {
      updateThreadName(data);

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

      result = hunt();  //關(guān)鍵步驟,獲取bitmap

      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)) {  //從內(nèi)存緩存處理
      bitmap = cache.get(key);
      if (bitmap != null) {
        stats.dispatchCacheHit();
        loadedFrom = MEMORY;
        if (picasso.loggingEnabled) {
          log(OWNER_HUNTER, VERB_DECODED, data.logId(), "from cache");
        }
        return bitmap;
      }
    }

    data.networkPolicy = retryCount == 0 ? NetworkPolicy.OFFLINE.index : networkPolicy;
    RequestHandler.Result result = requestHandler.load(data, networkPolicy);  //交由requestHandler獲取圖片
    if (result != null) {
      loadedFrom = result.getLoadedFrom();
      exifRotation = result.getExifOrientation();

      bitmap = result.getBitmap();

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

    if (bitmap != null) {
      if (picasso.loggingEnabled) {
        log(OWNER_HUNTER, VERB_DECODED, data.logId());
      }
      stats.dispatchBitmapDecoded(bitmap);
      if (data.needsTransformation() || exifRotation != 0) {
        synchronized (DECODE_LOCK) {
          if (data.needsMatrixTransform() || exifRotation != 0) {
            bitmap = transformResult(data, bitmap, exifRotation);  //對圖片進行變形等操作
            if (picasso.loggingEnabled) {
              log(OWNER_HUNTER, VERB_TRANSFORMED, data.logId());
            }
          }
          if (data.hasCustomTransformations()) {     //處理自定義的變形操作
            bitmap = applyCustomTransformations(data.transformations, bitmap);  
            if (picasso.loggingEnabled) {
              log(OWNER_HUNTER, VERB_TRANSFORMED, data.logId(), "from custom transformations");
            }
          }
        }
        if (bitmap != null) {
          stats.dispatchBitmapTransformed(bitmap);
        }
      }
    }

    return bitmap;
  }

圖片的獲取就完成后,再交由dispatcher去處理 dispatcher.dispatchComplete(this);

顯示

BitmapHunter獲取圖片成功后,會交由dispatcher.dispatchComplete(this);處理,最終會執(zhí)行到以下

 void performComplete(BitmapHunter hunter) {
    if (shouldWriteToMemoryCache(hunter.getMemoryPolicy())) {
      cache.set(hunter.getKey(), hunter.getResult());  //如果需要內(nèi)存緩存則添加到cache中
    }
    hunterMap.remove(hunter.getKey());
    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)) {  //如果沒有指定message則發(fā)送指定消息
      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);
  }

這里主要有一個batch處理讓人費解, dispatcher會以200ms為一個周期區(qū)處理complete任務(wù),至于為什么要有這個操作,個人猜測可能是基于性能考慮吧.
最終,dispatcher會將200ms內(nèi)完成的任務(wù)發(fā)送到主線程(這個主線程handler定義在Picasso類中),
主線程收到這個消息后會調(diào)用complete方法,來看看這個方法:

  void complete(BitmapHunter hunter) {
    Action single = hunter.getAction();
    List<Action> joined = hunter.getActions();

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

    if (single != null) {
      deliverAction(result, from, single);
    }

    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(result, from);
      if (loggingEnabled) {
        log(OWNER_MAIN, VERB_COMPLETED, action.request.logId(), "from " + from);
      }
    } else {
      action.error();
      if (loggingEnabled) {
        log(OWNER_MAIN, VERB_ERRORED, action.request.logId());
      }
    }
  }

最終,action.complete(result, from);會被調(diào)用,在這個方法里面會對target設(shè)置bitmap(還有些加載動畫等設(shè)置,此處不再贅述),至此圖片加載完成。

總結(jié)

Picasso獲取圖片資源并顯示的代碼流轉(zhuǎn)過程如下:

  1. Picasso.with()獲取Picasso實例
  2. .load("url")方法用傳入的url創(chuàng)建一個RequestCreator對象
  3. .into(imageview)方法創(chuàng)建此次request并將其封裝進action再調(diào)用picasso.enqueueAndSubmit(action)
  4. Picasso類將action對象交給dispatcher.submit()
  5. dispatcher類根據(jù)action創(chuàng)建bitmapHunter,并將bitmapHunter提交至線程池執(zhí)行

當(dāng)bitmapHunter獲取到圖片資源后,又經(jīng)過了以下步驟最終顯示在ImageView上

  1. bitmapHunter獲取圖片資源成功,調(diào)用dispatcher.dispatchComplete(this);
  2. dispatcher發(fā)送延遲200msmsg.what=HUNTER_DELAY_NEXT_BATCH、攜帶200ms內(nèi)完成的bitmapHunter封裝為一個list的消息到主線程
  3. 主線程收到消息后,調(diào)用Picasso類的complete方法,解析出bitmapHunter中的action
  4. actioncomplete方法內(nèi),將bitmap設(shè)置給Imageview

一次簡單的圖片加載雖然經(jīng)歷了這么多的步驟,但也換來了清晰的結(jié)構(gòu),強大的功能,良好的擴展性.而其中用到的設(shè)計模式也很值得學(xué)習(xí).

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容