圖解Picasso源碼

以下是picasso調(diào)用的圖解:


image

1.當(dāng)我們?cè)谡{(diào)用Picasso.with()方法的時(shí)候,會(huì)生成一個(gè)單例的Picasso

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

首先是全局的一個(gè)單例對(duì)象,其次是通過(guò)Builder模式生成對(duì)應(yīng)的Picasso對(duì)象。

2.我們?cè)谡{(diào)用完上面的方法之后,會(huì)繼續(xù)調(diào)用load方法:

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

支持loadFile,Uri,path等,在這里會(huì)其實(shí)最終都是調(diào)用load(uri)的方法,生成RequestCreator,接下來(lái)的placeHolder,errImage,設(shè)置圖片等,通過(guò)鏈?zhǔn)秸{(diào)用實(shí)現(xiàn)。

3.在創(chuàng)建完成RequestCreator之后,我們會(huì)執(zhí)行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()) {//1
      picasso.cancelRequest(target);
      if (setPlaceholder) {
        setPlaceholder(target, getPlaceholderDrawable());
      }
      return;
    }

    if (deferred) {
      if (data.hasSize()) {//2
        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)) {//3
      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) {//4
      setPlaceholder(target, getPlaceholderDrawable());
    }

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

    picasso.enqueueAndSubmit(action);//5
  }

在這里主要就是執(zhí)行圖片的獲取,轉(zhuǎn)換大小以及圖片的顯示的操作。

3.1 上面的第一步主要是判斷有沒(méi)有資源文件設(shè)置或者本地路徑等,如果有那么直接顯示,這里主要是變相地實(shí)現(xiàn)了Picasso的本地圖片的加載的實(shí)現(xiàn)。

3.2 第二步設(shè)置要顯示的ImageView控件的大小,以便計(jì)算圖片和控件的大小比,以進(jìn)行加載時(shí)候內(nèi)存的優(yōu)化

3.3 第三步會(huì)從內(nèi)存中去讀取圖片,讀取到圖片增加命中的計(jì)算器

3.4 第四步是設(shè)置空白圖片

3.5 第五步主要就是執(zhí)行圖片的獲取操作,picasso.enqueueAndSubmit(Action)方法:

4.picasso.enqueueAndSubmit(Action)方法:

void enqueueAndSubmit(Action action) {
    Object target = action.getTarget();//因?yàn)樵谏厦娴奈覀兂跏蓟腎mageView的Action,所以target是要加載的ImageView。
    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);
  }

在這里我們會(huì)調(diào)用submit方法,該方法主要是將action時(shí)間分發(fā)給對(duì)應(yīng)的Dispatcher,dispatcher.dispatchSubmit(action);

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

對(duì)應(yīng)的會(huì)通過(guò)Handler發(fā)送一個(gè)REQUEST_SUBMIT的消息,這個(gè)Handler是DispatcherHandler的實(shí)例對(duì)象,執(zhí)行對(duì)應(yīng)的HandleMessage方法,

 case REQUEST_SUBMIT: {
          Action action = (Action) msg.obj;
          dispatcher.performSubmit(action);
          break;
        }

5.我們來(lái)看看Dispatcher類(lèi)的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);//1
    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中會(huì)一次調(diào)用各種RequestHandler的canHandleRequest方法,來(lái)選擇能處理的RequestHandler
piassco在初始化的時(shí)候,默認(rèn)會(huì)添加如下的RequestHandler

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

6.上述找到對(duì)應(yīng)能處理的RequestHandler之后,創(chuàng)建對(duì)應(yīng)的bitmapHunter,BitmapHunder其實(shí)是Runnable的實(shí)現(xiàn)。

 @Override
  public Future<?> submit(Runnable task) {
    PicassoFutureTask ftask = new PicassoFutureTask((BitmapHunter) task);
    execute(ftask);
    return ftask;
  }

創(chuàng)建對(duì)應(yīng)的Runnable完成之后,加入線程池中執(zhí)行

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

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

      result = hunt();//1

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

注釋1是獲取圖片的邏輯


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

    if (shouldReadFromMemoryCache(memoryPolicy)) {//1
      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) {//2
      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) {//3
      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;
  }

上述注釋1就是從內(nèi)存中獲取圖片,如果取不到圖片注釋2由RequestHandler.load拿到圖片數(shù)據(jù)的流的結(jié)果對(duì)象,然后解析成圖片,注釋3在拿到圖片之后,對(duì)圖片根據(jù)控件的大小進(jìn)行轉(zhuǎn)換。拿到圖片之后,發(fā)送消息code為HUNTER_COMPLETE的消息到MessageQueue中,


      if (result == null) {
        dispatcher.dispatchFailed(this);
      } else {
        dispatcher.dispatchComplete(this);
      }

接著dispatcherHandler執(zhí)行

  case HUNTER_COMPLETE: {
          BitmapHunter hunter = (BitmapHunter) msg.obj;
          dispatcher.performComplete(hunter);
          break;
        }
 void performComplete(BitmapHunter hunter) {
    if (shouldWriteToMemoryCache(hunter.getMemoryPolicy())) {
      cache.set(hunter.getKey(), hunter.getResult());
    }
    hunterMap.remove(hunter.getKey());
    batch(hunter);//1
    if (hunter.getPicasso().loggingEnabled) {
      log(OWNER_DISPATCHER, VERB_BATCHED, getLogIdsForHunter(hunter), "for completion");
    }
  }

進(jìn)行內(nèi)存中保存。完成圖片的內(nèi)存緩存之后,就是對(duì)圖片設(shè)置到ImageView上,Dispatch的batch方法

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);
    }
  }
   case HUNTER_DELAY_NEXT_BATCH: {
          dispatcher.performBatchComplete();
          break;
        }
void performBatchComplete() {
    List<BitmapHunter> copy = new ArrayList<BitmapHunter>(batch);
    batch.clear();
    mainThreadHandler.sendMessage(mainThreadHandler.obtainMessage(HUNTER_BATCH_COMPLETE, copy));
    logBatch(copy);
  }

其實(shí)上面的操作是將io線程切換到主線程上來(lái),到綁定主線程Looper的handler接收到消息,會(huì)執(zhí)行

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

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

注釋1就是將圖片設(shè)置到Image的操作。

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

通過(guò)ImageViewAction執(zhí)行界面的設(shè)置操作。

總結(jié)

上面其實(shí)只是一個(gè)源碼的閱讀流程記錄而已,其實(shí)其中的更多的是設(shè)計(jì)思想的理解,設(shè)計(jì)模式的學(xué)習(xí)等,比如這里的Action接口,多個(gè)子類(lèi)實(shí)現(xiàn)了該接口,都會(huì)執(zhí)行compelete方法,這就是策略模式的模型,會(huì)根據(jù)你傳入的是ImageViewAction還是GetAction來(lái)執(zhí)行對(duì)應(yīng)的complete,這樣就需要判斷是ImageViewAction還是GetAction來(lái)執(zhí)行對(duì)應(yīng)的操作;還有在初始化的時(shí)候,會(huì)在list中增加各種RequestHandler,然后在根據(jù)你傳入的uri,找到對(duì)應(yīng)的RequestHandler這種設(shè)計(jì),個(gè)人覺(jué)得這種設(shè)計(jì)在解決一個(gè)問(wèn)題有多種串行的嘗試的時(shí)候,這個(gè)還是很有用。

如果你們覺(jué)得文章對(duì)你有啟示作用,希望你們幫忙點(diǎn)個(gè)贊或者關(guān)注下,謝謝。

?著作權(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)容

  • 一. 概述 Picasso是Square出品的一個(gè)非常精簡(jiǎn)的圖片加載及緩存庫(kù),其主要特點(diǎn)包括: 易寫(xiě)易讀的流式編程...
    SparkInLee閱讀 1,201評(píng)論 2 11
  • Picasso,看的版本是v.2.5.2 使用方法,大概這么幾種加載資源的形式 還可以對(duì)圖片進(jìn)行一些操作:設(shè)置大小...
    Jinjins1129閱讀 411評(píng)論 0 3
  • 我每周會(huì)寫(xiě)一篇源代碼分析的文章,以后也可能會(huì)有其他主題.如果你喜歡我寫(xiě)的文章的話,歡迎關(guān)注我的新浪微博@達(dá)達(dá)達(dá)達(dá)s...
    SkyKai閱讀 4,117評(píng)論 10 37
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,983評(píng)論 25 709
  • 良知者,末學(xué)解為人之本心本性?;蛞嗫山鉃樾惺轮跣囊病?心有良知之人,志氣必定堅(jiān)若磐石,百般誘惑亦難撼動(dòng)。正所謂富...
    游弋的蝦米閱讀 605評(píng)論 0 0

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