圖解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類的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è)子類實(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)系作者
  • 序言:七十年代末直颅,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子怀樟,更是在濱河造成了極大的恐慌功偿,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,311評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件往堡,死亡現(xiàn)場(chǎng)離奇詭異械荷,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)虑灰,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,339評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門吨瞎,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人穆咐,你說(shuō)我怎么就攤上這事关拒。” “怎么了庸娱?”我有些...
    開封第一講書人閱讀 152,671評(píng)論 0 342
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)谐算。 經(jīng)常有香客問(wèn)我熟尉,道長(zhǎng),這世上最難降的妖魔是什么洲脂? 我笑而不...
    開封第一講書人閱讀 55,252評(píng)論 1 279
  • 正文 為了忘掉前任斤儿,我火速辦了婚禮剧包,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘往果。我一直安慰自己疆液,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,253評(píng)論 5 371
  • 文/花漫 我一把揭開白布陕贮。 她就那樣靜靜地躺著堕油,像睡著了一般。 火紅的嫁衣襯著肌膚如雪肮之。 梳的紋絲不亂的頭發(fā)上掉缺,一...
    開封第一講書人閱讀 49,031評(píng)論 1 285
  • 那天,我揣著相機(jī)與錄音戈擒,去河邊找鬼眶明。 笑死,一個(gè)胖子當(dāng)著我的面吹牛筐高,可吹牛的內(nèi)容都是我干的搜囱。 我是一名探鬼主播,決...
    沈念sama閱讀 38,340評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼柑土,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼蜀肘!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起冰单,我...
    開封第一講書人閱讀 36,973評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤幌缝,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后诫欠,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體涵卵,經(jīng)...
    沈念sama閱讀 43,466評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,937評(píng)論 2 323
  • 正文 我和宋清朗相戀三年荒叼,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了轿偎。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,039評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡被廓,死狀恐怖坏晦,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情嫁乘,我是刑警寧澤昆婿,帶...
    沈念sama閱讀 33,701評(píng)論 4 323
  • 正文 年R本政府宣布,位于F島的核電站蜓斧,受9級(jí)特大地震影響仓蛆,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜挎春,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,254評(píng)論 3 307
  • 文/蒙蒙 一看疙、第九天 我趴在偏房一處隱蔽的房頂上張望豆拨。 院中可真熱鬧,春花似錦能庆、人聲如沸施禾。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,259評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)弥搞。三九已至,卻和暖如春丰涉,著一層夾襖步出監(jiān)牢的瞬間拓巧,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,485評(píng)論 1 262
  • 我被黑心中介騙來(lái)泰國(guó)打工一死, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留肛度,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,497評(píng)論 2 354
  • 正文 我出身青樓投慈,卻偏偏與公主長(zhǎng)得像承耿,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子伪煤,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,786評(píng)論 2 345

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

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