Picasso源碼揭祕

Picasso做爲圖片處理的主流庫之一,很是有名,今天咱們就從源碼的層面上解析他。
首先是picasso的典型用法:緩存

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

Picasso.with(context)
    .load(url)
    .resize(width,height)
    .centerInside().into(imageView);

Picasso .with(context)
    .load(url)
    .placeholder(R.drawable.loading)
    .error(R.drawable.error)
    .into(imageView);

能夠看到,很是簡單。那麼咱們就從這些調用入手逐步查看代碼。安全

初始化

Picasso.with(@NonNull Context context):網絡

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

能夠看到幾點信息:
1.static方法,使用起來很方便,屏蔽了大量的參數,讓他們在後面逐步加入;
2.整個Picasso採用單例模式,Picasso的設計就是承擔不少工做的引擎,所以佔用資源較多,沒有必要在一個app中出現多個,也爲了節省資源和提升效率,採用了單例模式;
3.建立單例的實例的時候,new出了Builder,並傳入context,以後調用Builder的build來創建單例;
4.使用synchronized來保證創建單例實例的過程是線程安全的;併發

簡單看下build方法:app

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

這裏纔是Picasso對象實例真正建立的地方。那麼以前的這些操做是在初始化環境:
1.downloader下載器的創建;
2.cache的創建;
3.service線程池的創建;
4.RequestTransformer的創建;
再從結構上看,能夠看出Picasso的單例的建立採用的是build模式。若是哪天想修改Picasso的上述組件的設置,又不想暴露給調用者,那麼就能夠再寫一個build,重寫這些代碼並替換相關組件,同時在with層面上修改調用便可。異步

下面再來看看Picasso的構造:ide

Picasso(Context context, Dispatcher dispatcher, Cache cache, Listener listener,
      RequestTransformer requestTransformer, List<RequestHandler> extraRequestHandlers, Stats stats,
      Bitmap.Config defaultBitmapConfig, boolean indicatorsEnabled, boolean loggingEnabled) {
    this.context = context;
    this.dispatcher = dispatcher;
    this.cache = cache;
    this.listener = listener;
    this.requestTransformer = requestTransformer;
    this.defaultBitmapConfig = defaultBitmapConfig;

    int builtInHandlers = 7; // Adjust this as internal handlers are added or removed.
    int extraCount = (extraRequestHandlers != null ? extraRequestHandlers.size() : 0);
    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);

    this.stats = stats;
    this.targetToAction = new WeakHashMap<Object, Action>();
    this.targetToDeferredRequestCreator = new WeakHashMap<ImageView, DeferredRequestCreator>();
    this.indicatorsEnabled = indicatorsEnabled;
    this.loggingEnabled = loggingEnabled;
    this.referenceQueue = new ReferenceQueue<Object>();
    this.cleanupThread = new CleanupThread(referenceQueue, HANDLER);
    this.cleanupThread.start();
  }

創建了allRequestHandlers,默認提供7個,另外還可創建擴展,擴展是能夠從構造傳遞過來參數創建的。這裏只簡單看下requestHandler,以FileRequestHandler爲例:函數

class FileRequestHandler extends ContentStreamRequestHandler {

  FileRequestHandler(Context context) {
    super(context);
  }

  @Override public boolean canHandleRequest(Request data) {
    return SCHEME_FILE.equals(data.uri.getScheme());
  }

  @Override public Result load(Request request, int networkPolicy) throws IOException {
    return new Result(null, getInputStream(request), DISK, getFileExifRotation(request.uri));
  }

  static int getFileExifRotation(Uri uri) throws IOException {
    ExifInterface exifInterface = new ExifInterface(uri.getPath());
    return exifInterface.getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL);
  }
}

能夠看到,FileRequestHandler是處理請求的輔助的角色,;load裏面的result加載的方式是disk,基本能夠肯定是直接從磁盤上讀取文件。後面還會有調用,這裏暫時再也不詳述。
再回到Picasso的構造,注意:requestHandlers = Collections.unmodifiableList(allRequestHandlers);這句話是重構容器,並生成一個只讀不可寫的容器對象。也就是說,一旦開始Picasso就肯定的這些requesthandler,在運行期間不可再擴展添加。
再看cleanupThread:oop

@Override public void run() {
      Process.setThreadPriority(THREAD_PRIORITY_BACKGROUND);
      while (true) {
        try {
          // Prior to Android 5.0, even when there is no local variable, the result from
          // remove() & obtainMessage() is kept as a stack local variable.
          // We're forcing this reference to be cleared and replaced by looping every second
          // when there is nothing to do.
          // This behavior has been tested and reproduced with heap dumps.
          RequestWeakReference<?> remove =
              (RequestWeakReference<?>) referenceQueue.remove(THREAD_LEAK_CLEANING_MS);
          Message message = handler.obtainMessage();
          if (remove != null) {
            message.what = REQUEST_GCED;
            message.obj = remove.action;
            handler.sendMessage(message);
          } else {
            message.recycle();
          }
        } catch (InterruptedException e) {
          break;
        } catch (final Exception e) {
          handler.post(new Runnable() {
            @Override public void run() {
              throw new RuntimeException(e);
            }
          });
          break;
        }
      }
    }

一個死循環,不斷的從referenceQueue隊列中移除request,而後對主線程的handler發送gced的消息。這個線程就是一個垃圾回收的線程。
至此,初始化的過程結束了。post

參數設置

隨便看下load函數:

public RequestCreator load(@Nullable 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);
  }

最重要的是產生了一個Request.Builder,爲後面創建request作準備。
回到load調用,由於返回的是RequestCreator對象,所以後續的處理都是針對他的,例如resize方法:

public RequestCreator resize(int targetWidth, int targetHeight) {
    data.resize(targetWidth, targetHeight);
    return this;
  }

resize其實是在調用data也就是Request.Builder的resize方法處理圖片的大小設置。再進一步看下去:

public Builder resize(int targetWidth, int targetHeight) {
      if (targetWidth < 0) {
        throw new IllegalArgumentException("Width must be positive number or 0.");
      }
      if (targetHeight < 0) {
        throw new IllegalArgumentException("Height must be positive number or 0.");
      }
      if (targetHeight == 0 && targetWidth == 0) {
        throw new IllegalArgumentException("At least one dimension has to be positive number.");
      }
      this.targetWidth = targetWidth;
      this.targetHeight = targetHeight;
      return this;
    }

只是將寬高的參數保留起來。看到這裏大致可以明白picasso的一個操做邏輯了,前期的這些設置都是做爲參數保留下來的,只有最後真正執行的時候再讀取這些參數進行相應的操做。那麼這種模式能夠理解爲將複雜的很是多的參數進行了鏈式的保存和歸類,便於調用者的理解和操做簡化,須要的進行設置,不須要的跳過。每次進行設置都返回RequestCreator。
那麼要在什麼地方進行實際的操做呢?咱們下面來看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);
  }

這段代碼最後要調用picasso.enqueueAndSubmit(action);就是實際提交請求了。後面咱們再進去具體看。setPlaceholder進行佔位符的判斷,deferred用來進行是否延遲加載的斷定,shouldReadFromMemoryCache來肯定緩存加載策略並執行相關邏輯。最後建立一個Action,並提交這個action。
首先咱們來看看action,代碼就不貼了,基本上就是個容器類,用來存儲請求的一些信息,而且是個抽象類。須要注意的是對target的保存,使用的是弱引用,爲了避免形成內存泄露。這個target就是要顯示圖片的view。action的子類承擔的工做都是下載圖片等,須要覆蓋幾個抽象方法來處理完成(設置view圖像)、錯誤和取消等狀況。那麼幾乎能夠確定大部分的真正的走網處理都在picasso.enqueueAndSubmit(action);裏面了。這裏回顧下,這種設計方式將請求做爲了一連串的參數數據保存在action裏,執行在另外的地方作,就是一個基本的數據與邏輯的分離,解耦。可以將邏輯的處理標準化,而數據的樣式能夠隨着擴展多樣化。
下面繼續看enqueueAndSubmit:

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

最主要的幹了一件事:submit,那麼這個submit作了什麼呢?

void submit(Action action) {
    dispatcher.dispatchSubmit(action);
  }

到達這裏,進入了Dispatcher,Dispatcher在build的初始化階段就創建好了,是進行action派發的機構。

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

利用handler將action發送了出去,那麼看看handler,是個DispatcherHandler,裏面的最重要的handleMessage,根據參數不一樣作出了相關處理:

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

這個dispatcher就是Dispatcher的引用,實際上最後仍是在調用Dispatcher,但爲何繞這個圈呢?緣由在於:

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

看到了吧,這裏用了DispatcherThread(HandlerThread的子類),而且將looper傳遞給了DispatcherHandler。也就是說,DispatcherHandler的處理過程運行在了其餘線程裏,做爲異步操做了,包括調用的Dispatcher的dispatcher.performSubmit(action);等方法都是如此。這裏巧妙的運用了DispatcherThread實現了異步線程操做,避免了ui線程的等待。那麼HandlerThread是什麼呢?簡單的講就是帶有消息循環looper的線程,會不斷的處理消息。那麼這麼分離使action的處理都獨立到了線程中。
下面來看Dispatcher的performSubmit:

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

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

1.是否該請求被暫停,若是是放入暫停action的map裏;
2.從hunterMap中查找是否已經有相同uri的BitmapHunter,若是有合併返回;
3.經過forRequest建立hunter;
4.提交線程池,並加入hunterMap中;
重點在於forRequest和提交線程池。先看下forRequest:

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

1.從action中得到request;
2.根據request依次到requestHandlers中的每一個requestHandler判斷是否可處理(還記得requestHandlers一共默認有7個,還可擴展);
3.若是可被一個requestHandler處理,則new出BitmapHunter,並傳遞這個requestHandler進入;
這裏的處理方式是個標準的鏈式,依次詢問每一個處理者是否能夠,能夠交付,不能夠繼續。很是適合少許的處理者,而且請求和處理者是一對一關係的狀況。

下面回來看線程池,service.submit(hunter);,這個BitmapHunter是個runnable,提交後就會在線程池分配的線程中運行hunter的run:

@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
    ...
  }

1.更新線程名字,這裏須要注意的是NAME_BUILDER,是個ThreadLocal對象,就是會爲每一個線程分離出一個對象,防止併發線程改寫該對象形成的數據錯亂,具體概念不說了,能夠具體查查看。
2.調用hunt方法返回結果,重點,一下子看;
3.調用dispatcher.dispatchComplete(this);或dispatcher.dispatchFailed(this);進行收尾的處理;
4.異常處理;
下面看看hunt方法:

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

    if (shouldReadFromMemoryCache(memoryPolicy)) {
      bitmap = cache.get(key);
      if (bitmap != null) {
        stats.dispatchCacheHit();
        loadedFrom = MEMORY;
        if (picasso.loggingEnabled) {
          log(OWNER_HUNTER, VERB_DECODED, data.logId(), "from cache");
        }
        return bitmap;
      }
    }

    data.networkPolicy = retryCount == 0 ? NetworkPolicy.OFFLINE.index : networkPolicy;
    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);
      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);
        }
      }
    }

    return bitmap;
  }

1.根據策略檢查是否可直接從內存中獲取,若是能夠加載並返回;
2.經過requestHandler.load(data, networkPolicy);去獲取返回數據。重點;
3.根據以前設置的參數處理Transformation;

從requestHandler.load看起,requestHandler是個抽象類,那麼咱們就從NetworkRequestHandler這個比較經常使用的子類看起,看他的load方法:

@Override @Nullable public Result load(Request request, int networkPolicy) throws IOException {
    Response response = downloader.load(request.uri, request.networkPolicy);
    if (response == null) {
      return null;
    }

    Picasso.LoadedFrom loadedFrom = response.cached ? DISK : NETWORK;

    Bitmap bitmap = response.getBitmap();
    if (bitmap != null) {
      return new Result(bitmap, loadedFrom);
    }

    InputStream is = response.getInputStream();
    if (is == null) {
      return null;
    }
    // Sometimes response content length is zero when requests are being replayed. Haven't found
    // root cause to this but retrying the request seems safe to do so.
    if (loadedFrom == DISK && response.getContentLength() == 0) {
      Utils.closeQuietly(is);
      throw new ContentLengthException("Received response with 0 content-length header.");
    }
    if (loadedFrom == NETWORK && response.getContentLength() > 0) {
      stats.dispatchDownloadFinished(response.getContentLength());
    }
    return new Result(is, loadedFrom);
  }

1.經過downloader.load進行了下載活動,重點;
2.根據response.cached肯定從磁盤或網絡加載;
3.若是是網絡加載,須要走dispatchDownloadFinished,裏面發送了DOWNLOAD_FINISHED請求,告知下載完成;

下面進入到downloader了,Downloader又是個抽象類,實現有3個,OkHttp3Downloader、OkHttpDownloader、UrlConnectionDownloader。默認>9以上使用OkHttp3Downloader,備用使用OkHttpDownloader,都不行使用UrlConnectionDownloader。咱們以OkHttp3Downloader爲例看看:

@Override public Response load(@NonNull Uri uri, int networkPolicy) throws IOException {
    CacheControl cacheControl = null;
    if (networkPolicy != 0) {
      if (NetworkPolicy.isOfflineOnly(networkPolicy)) {
        cacheControl = CacheControl.FORCE_CACHE;
      } else {
        CacheControl.Builder builder = new CacheControl.Builder();
        if (!NetworkPolicy.shouldReadFromDiskCache(networkPolicy)) {
          builder.noCache();
        }
        if (!NetworkPolicy.shouldWriteToDiskCache(networkPolicy)) {
          builder.noStore();
        }
        cacheControl = builder.build();
      }
    }

    Request.Builder builder = new okhttp3.Request.Builder().url(uri.toString());
    if (cacheControl != null) {
      builder.cacheControl(cacheControl);
    }

    okhttp3.Response response = client.newCall(builder.build()).execute();
    int responseCode = response.code();
    if (responseCode >= 300) {
      response.body().close();
      throw new ResponseException(responseCode + " " + response.message(), networkPolicy,
          responseCode);
    }

    boolean fromCache = response.cacheResponse() != null;

    ResponseBody responseBody = response.body();
    return new Response(responseBody.byteStream(), fromCache, responseBody.contentLength());
  }

1.檢查網絡策略,若是須要從緩存裏拿;
2.標準的okhttp使用下載圖片;

最後回來看下Dispatcher的dispatchComplete方法,會給ThreadHandler發送HUNTER_COMPLETE消息,而在handleMessage裏面會最終走到dispatcher.performComplete(hunter);

void performComplete(BitmapHunter hunter) {
    if (shouldWriteToMemoryCache(hunter.getMemoryPolicy())) {
      cache.set(hunter.getKey(), hunter.getResult());
    }
    hunterMap.remove(hunter.getKey());
    batch(hunter);
    if (hunter.getPicasso().loggingEnabled) {
      log(OWNER_DISPATCHER, VERB_BATCHED, getLogIdsForHunter(hunter), "for completion");
    }
  }

1.寫緩存;
2.從hunterMap中移除本次hunter;
3.batch(hunter);內部是延遲發送了一個HUNTER_DELAY_NEXT_BATCH消息;
在handlehandleMessage裏面走的是dispatcher.performBatchComplete();注意到此爲止都在異步線程中運做。看看這個函數:

void performBatchComplete() {
    List<BitmapHunter> copy = new ArrayList<BitmapHunter>(batch);
    batch.clear();
    mainThreadHandler.sendMessage(mainThreadHandler.obtainMessage(HUNTER_BATCH_COMPLETE, copy));
    logBatch(copy);
  }

往主線程發送了HUNTER_BATCH_COMPLETE。在Picasso的主線程handler中的處理是:

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

最終是走到了Picasso的complete方法中,這裏實際上處理了完成的hunter。complete的關鍵就是一句話:deliverAction調用,而這裏的關鍵是action.complete(result, from);一個抽象方法,最後看看ImageViewAction:

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

不用再解釋什麼了吧。這彎兒繞的。
至此分析完畢。

寫在最後

參數的設置過程和分類很好,除了主線程外,起了一個線程用來處理dispicher,沒有使用併發,而是使用looper線程,後面採用線程池進行下載的操做。各個環節擴展性都很好,action/requesthander/downloader等。有興趣的能夠再看看這裏的LruCache,對LinkedHashMap的使用也是不錯的。

相關文章
相關標籤/搜索