Picasso源碼解析

Picasso源碼解析(本文基於Picasso2.4.0版本)

Picasso加載圖片最簡單的調用方法是

Picasso.with(mContext).load(url).into(iv);

我們一起來看看這三個方法裏面做了什麼

方法解析

1.with

這個方法首先會返回一個單例的Picasso對象(裏面用了兩個判斷一把鎖的單例模式)

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

    return singleton;
}

如果是第一次創建,會對Picasso進行初始化,主要的有Cache,線程池,downloader,Dispatcher

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, stats, debugging);
    }
}

(1) Cache:是一個LruCache 他的最大緩存大小大約是15%(通過下面的方法計算的)

static int calculateMemoryCacheSize(Context context) {
    ActivityManager am = getService(context, ACTIVITY_SERVICE);
    boolean largeHeap = (context.getApplicationInfo().flags & FLAG_LARGE_HEAP) != 0;
    int memoryClass = am.getMemoryClass();
    if (largeHeap && SDK_INT >= HONEYCOMB) {
      memoryClass = ActivityManagerHoneycomb.getLargeMemoryClass(am);
    }
    // Target ~15% of the available heap.
    return 1024 * 1024 * memoryClass / 7;
  }

(2) 線程池:會根據不同的網絡狀態來改變核心線程的數量(動態設置線程數量的代碼在下面,可以作爲以後封裝線程池的參考)

  void adjustThreadCount(NetworkInfo info) {
if (info == null || !info.isConnectedOrConnecting()) {
  setThreadCount(DEFAULT_THREAD_COUNT);
  return;
}
switch (info.getType()) {
  case ConnectivityManager.TYPE_WIFI:
  case ConnectivityManager.TYPE_WIMAX:
  case ConnectivityManager.TYPE_ETHERNET:
    setThreadCount(4);
    break;
  case ConnectivityManager.TYPE_MOBILE:
    switch (info.getSubtype()) {
      case TelephonyManager.NETWORK_TYPE_LTE:  // 4G
      case TelephonyManager.NETWORK_TYPE_HSPAP:
      case TelephonyManager.NETWORK_TYPE_EHRPD:
        setThreadCount(3);
        break;
      case TelephonyManager.NETWORK_TYPE_UMTS: // 3G
      case TelephonyManager.NETWORK_TYPE_CDMA:
      case TelephonyManager.NETWORK_TYPE_EVDO_0:
      case TelephonyManager.NETWORK_TYPE_EVDO_A:
      case TelephonyManager.NETWORK_TYPE_EVDO_B:
        setThreadCount(2);
        break;
      case TelephonyManager.NETWORK_TYPE_GPRS: // 2G
      case TelephonyManager.NETWORK_TYPE_EDGE:
        setThreadCount(1);
        break;
      default:
        setThreadCount(DEFAULT_THREAD_COUNT);
    }
    break;
  default:
    setThreadCount(DEFAULT_THREAD_COUNT);
}

}

(3) downloader:他會根據你是否有集成Okhttp,如果有就用Okhttp,如果有就用OkhttpDowmLoader,沒有就自己創建一個UrlConnectionDownloader(通過反射,看是否集成了okhttp)

static Downloader createDefaultDownloader(Context context) {
    try {
      Class.forName("com.squareup.okhttp.OkHttpClient");
      return OkHttpLoaderCreator.create(context);
    } catch (ClassNotFoundException ignored) {
    }
    return new UrlConnectionDownloader(context);
  }

(4) Dispatcher裏面主要是開了一個子線程,並創建了一個該線程的handler(核心代碼)

this.handler = new DispatcherHandler(dispatcherThread.getLooper(), this);

2.load

這個方法很多重載,但最終會走load(uri)或load(id).這裏主要返回了一個RequestCreator,並且創建了一個Request.Builder對象並賦值給了他的data字段.

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

RequestCreator的構造方法(創建了一個Request.Builder對象並賦值給了他的data字段)

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

3.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()) {
      picasso.cancelRequest(target);
      if (setPlaceholder) {
        setPlaceholder(target, getPlaceholderDrawable());
      }
      return;
    }

    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) {
        if (setPlaceholder) {
          setPlaceholder(target, getPlaceholderDrawable());
        }
        picasso.defer(target, new DeferredRequestCreator(this, target, callback));
        return;
      }
      data.resize(width, height);
    }

    Request request = createRequest(started);
    String requestKey = createKey(request);

    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 =
        new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
            errorDrawable, requestKey, tag, callback, noFade);

    picasso.enqueueAndSubmit(action);
  }

(1)檢查是否是主線程,不是就報錯

checkMain()

(2)檢查是否設了uri或者id,沒設的話就直接顯示placeholder圖片.

if (!data.hasImage()) {
  picasso.cancelRequest(target);//取消之前的任務
  if (setPlaceholder) {
    setPlaceholder(target, getPlaceholderDrawable());//顯示placeholder圖片
  }
  return;
}

(3)檢查是否調用了fit(),如果是,代表需要將image調整爲ImageView的大小
(之後會根據這個數值進行壓縮)

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) {
    if (setPlaceholder) {
      setPlaceholder(target, getPlaceholderDrawable());
    }
    picasso.defer(target, new DeferredRequestCreator(this, target, callback));
    return;
  }
  data.resize(width, height);
}

(4)嘗試從內存中中獲取圖片,如果獲取到了,那麼就顯示,並且結束

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

(5)如果沒有接着又會讓顯示placeholder圖片

if (setPlaceholder) {
  setPlaceholder(target, getPlaceholderDrawable());
}

(6)然後整個請求會被封裝成一個Action,並處理這個請求

Action action = new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
        errorDrawable, requestKey, tag, callback, noFade);
picasso.enqueueAndSubmit(action);

(7)如果以前這個iv已經有Action了,那麼就把以前的Action替換掉,並調用dispatcher.dispatchCancel方法去處理
(裏面會調用dispatcher的handler去處理,最終在子線程把該任務取消,這也就是爲什麼listview複用imageview不會錯位顯示的原因)**

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

(8)接着會調用dispatcher.dispatchSubmit,也是通過Handler在子線程中處理.

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

(9)接着會走到dispatcher的performSubmit方法(核心代碼如下,先簡單看看,下面會繼續做分析)

    BitmapHunter hunter = hunterMap.get(action.getKey());
    if (hunter != null) {
      hunter.attach(action);
      return;
    }

    hunter = forRequest(action.getPicasso(), this, cache, stats, action);
    hunter.future = service.submit(hunter);
    hunterMap.put(action.getKey(), hunter);

(10)forRequest方法會返回一個BitmapHunter,他會根據你傳的uri和id去獲取RequestHandler並賦值給BitmapHunter的一個屬

(11)接着會把這個BitmapHunter添加到線程池裏,他其實也是一個Runnable

(12)當線程池處理這個任務時.會走BitmapHunter的run方法,裏面主要就是調用了自己的hunt方法來獲取bitmap,並根據返回結果,調用dispatcher在子線程中進行不同的處理

  result = hunt();
  if (result == null) {
    dispatcher.dispatchFailed(this);
  } else {
    //如果是成功的話 會根據你的MemoryPolicy來決定是否保存在內存中
    dispatcher.dispatchComplete(this);
  }

(13)hunt方法的核心代碼如下(先簡單看看,下面會繼續做分析)

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

    //嘗試從內存中讀取
    if (shouldReadFromMemoryCache(memoryPolicy)) {
      bitmap = cache.get(key);
      if (bitmap != null) {
        stats.dispatchCacheHit();
        loadedFrom = MEMORY;
        return bitmap;
      }
    }

    //核心代碼
    data.networkPolicy = retryCount == 0 ? NetworkPolicy.OFFLINE.index : networkPolicy;
    RequestHandler.Result result = requestHandler.load(data, networkPolicy);
    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);
        }
      }
    }

    //對bitmap做預處理
    if (bitmap != null) {
      stats.dispatchBitmapDecoded(bitmap);
      if (data.needsTransformation() || exifRotation != 0) {
        synchronized (DECODE_LOCK) {
          if (data.needsMatrixTransform() || exifRotation != 0) {
            bitmap = transformResult(data, bitmap, exifRotation);
          }
        ...
      }
    }

    return bitmap;
  }

(14)hunt方法首先會再次嘗試從內存中讀取圖片,如果成功,就結束

    //嘗試從內存中讀取
    if (shouldReadFromMemoryCache(memoryPolicy)) {
      bitmap = cache.get(key);
      if (bitmap != null) {
        stats.dispatchCacheHit();
        loadedFrom = MEMORY;
        return bitmap;
      }
    }

(15)如果不行,會調用RequestHandler的load方法,因爲剛纔forRequest方法根據uri和id返回了不同的RequestHandler子類給到BitmapHunter中,而不同的RequestHandler子類重寫了不同了load方法.

RequestHandler.Result result = requestHandler.load(data, networkPolicy);

(16)這些RequestHandler子類是在Picasso的構造函數中創建的

  Picasso(Context context, Dispatcher dispatcher, Cache cache, Listener listener,
    ...
    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);
    ...
  }

(17)如果你的uri是網絡地址的話 走的是NetworkRequestHandler的load方法

(1)這裏有個細節就是Utils類裏面初始化了本地緩存的路徑和大小,在getCacheDir()的picasso-cache目錄下,大小爲2%的SD內存,最小5MB最大50MB

(2)load方法裏面主要用okhttp的同步請求,而且會根據你的networkPolicy來決定從內存還是本地,還是直接衝網絡讀取.

(18)load方法走完後會返回一個bitmap或者InputStream.
(如果是bitmap的話,其實已經對bitmap做了壓縮處理,如果是InputStream,也會接着對讀處理的bitmap做壓縮處理)

if (result != null) {
 ...
  bitmap = result.getBitmap();

  if (bitmap == null) {
    InputStream is = result.getStream();
    try {
      bitmap = decodeStream(is, data);//壓縮處理,想要詳細瞭解的可以進這個方法看
    } finally {
      Utils.closeQuietly(is);
    }
  }
}
如果圖片的寬高大於target的寬高的話,會按比例壓縮(如果寬是2倍,高是3倍,那麼壓縮2倍)
例:imageview的寬高都是100,圖片的寬是200,高是300,那麼圖片會被壓縮兩倍,也就是寬100,高150.

(19)接着會看圖片是否需要預處理,如果需要,那麼就進行預處理

  if (data.needsTransformation() || exifRotation != 0) {
    synchronized (DECODE_LOCK) {
      if (data.needsMatrixTransform() || exifRotation != 0) {
        bitmap = transformResult(data, bitmap, exifRotation);      
      }
      if (data.hasCustomTransformations()) {
        bitmap = applyCustomTransformations(data.transformations, bitmap);

      }
    }
    if (bitmap != null) {
      stats.dispatchBitmapTransformed(bitmap);
    }
  }

這裏加了鎖,保證在同一時間,系統只在解析一個圖片,防止多線程解析,出現OOM風險,也減少了同一時刻對硬件設備的性能開銷。

(20)BitmapHunter的hunt方法走完會回到他的run方法中並根據返回結果,調用dispatcher在子線程中進行不同的處理(即步驟12)

  result = hunt();
  if (result == null) {
    dispatcher.dispatchFailed(this);
  } else {
    //如果是成功的話 會根據你的MemoryPolicy來決定是否保存在內存中
    dispatcher.dispatchComplete(this);
  }

3.後續

Picasso的源碼分析大致就是這樣,但是我們看源碼最重要的原因是爲了學習裏面的代碼和原理,並應用到我們的項目中,所以接下來我會總結一下我在項目中如何對圖片加載進行相應的優化和封裝,敬請期待吧~

發佈了30 篇原創文章 · 獲贊 228 · 訪問量 46萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章