成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

Picasso源碼揭秘

k00baa / 1084人閱讀

摘要:作為圖片處理的主流庫之一,非常有名,今天我們就從源碼的層面上解析他。至此,初始化的過程結(jié)束了。首先我們來看看,代碼就不貼了,基本上就是個(gè)容器類,用來存儲(chǔ)請(qǐng)求的一些信息,并且是個(gè)抽象類。

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

可以看到,非常簡單。那么我們就從這些調(diào)用入手逐步查看代碼。

初始化

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

可以看到幾點(diǎn)信息:
1.static方法,使用起來很方便,屏蔽了大量的參數(shù),讓他們?cè)诤竺嬷鸩郊尤耄?br>2.整個(gè)Picasso采用單例模式,Picasso的設(shè)計(jì)就是承擔(dān)很多工作的引擎,因此占用資源較多,沒有必要在一個(gè)app中出現(xiàn)多個(gè),也為了節(jié)省資源和提高效率,采用了單例模式;
3.創(chuàng)建單例的實(shí)例的時(shí)候,new出了Builder,并傳入context,之后調(diào)用Builder的build來建立單例;
4.使用synchronized來保證建立單例實(shí)例的過程是線程安全的;

簡單看下build方法:

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對(duì)象實(shí)例真正創(chuàng)建的地方。那么之前的這些操作是在初始化環(huán)境:
1.downloader下載器的建立;
2.cache的建立;
3.service線程池的建立;
4.RequestTransformer的建立;
再從結(jié)構(gòu)上看,可以看出Picasso的單例的創(chuàng)建采用的是build模式。如果哪天想修改Picasso的上述組件的設(shè)置,又不想暴露給調(diào)用者,那么就可以再寫一個(gè)build,重寫這些代碼并替換相關(guān)組件,同時(shí)在with層面上修改調(diào)用即可。

下面再來看看Picasso的構(gòu)造:

Picasso(Context context, Dispatcher dispatcher, Cache cache, Listener listener,
      RequestTransformer requestTransformer, List 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 allRequestHandlers =
        new ArrayList(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();
    this.targetToDeferredRequestCreator = new WeakHashMap();
    this.indicatorsEnabled = indicatorsEnabled;
    this.loggingEnabled = loggingEnabled;
    this.referenceQueue = new ReferenceQueue();
    this.cleanupThread = new CleanupThread(referenceQueue, HANDLER);
    this.cleanupThread.start();
  }

建立了allRequestHandlers,默認(rèn)提供7個(gè),另外還可建立擴(kuò)展,擴(kuò)展是可以從構(gòu)造傳遞過來參數(shù)建立的。這里只簡單看下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);
  }
}

可以看到,F(xiàn)ileRequestHandler是處理請(qǐng)求的輔助的角色,;load里面的result加載的方式是disk,基本可以確定是直接從磁盤上讀取文件。后面還會(huì)有調(diào)用,這里暫時(shí)不再詳述。
再回到Picasso的構(gòu)造,注意:requestHandlers = Collections.unmodifiableList(allRequestHandlers);這句話是重構(gòu)容器,并生成一個(gè)只讀不可寫的容器對(duì)象。也就是說,一旦開始Picasso就確定的這些requesthandler,在運(yùn)行期間不可再擴(kuò)展添加。
再看cleanupThread:

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

一個(gè)死循環(huán),不斷的從referenceQueue隊(duì)列中移除request,然后對(duì)主線程的handler發(fā)送gced的消息。這個(gè)線程就是一個(gè)垃圾回收的線程。
至此,初始化的過程結(jié)束了。

參數(shù)設(shè)置

隨便看下load函數(shù):

public RequestCreator load(@Nullable Uri uri) {
    return new RequestCreator(this, uri, 0);
  }

非常簡單,只是創(chuàng)建并返回了一個(gè)RequestCreator對(duì)象。那么就來看看這個(gè)對(duì)象:

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

最重要的是產(chǎn)生了一個(gè)Request.Builder,為后面建立request做準(zhǔn)備。
回到load調(diào)用,因?yàn)榉祷氐氖荝equestCreator對(duì)象,因此后續(xù)的處理都是針對(duì)他的,例如resize方法:

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

resize實(shí)際上是在調(diào)用data也就是Request.Builder的resize方法處理圖片的大小設(shè)置。再進(jìn)一步看下去:

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

只是將寬高的參數(shù)保留起來??吹竭@里大體能夠明白picasso的一個(gè)操作邏輯了,前期的這些設(shè)置都是作為參數(shù)保留下來的,只有最后真正執(zhí)行的時(shí)候再讀取這些參數(shù)進(jìn)行相應(yīng)的操作。那么這種模式可以理解為將復(fù)雜的非常多的參數(shù)進(jìn)行了鏈?zhǔn)降谋4婧蜌w類,便于調(diào)用者的理解和操作簡化,需要的進(jìn)行設(shè)置,不需要的跳過。每次進(jìn)行設(shè)置都返回RequestCreator。
那么要在什么地方進(jìn)行實(shí)際的操作呢?我們下面來看into。

實(shí)際請(qǐng)求
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);
  }

這段代碼最后要調(diào)用picasso.enqueueAndSubmit(action);就是實(shí)際提交請(qǐng)求了。后面我們?cè)龠M(jìn)去具體看。setPlaceholder進(jìn)行占位符的判斷,deferred用來進(jìn)行是否延遲加載的判定,shouldReadFromMemoryCache來確定緩存加載策略并執(zhí)行相關(guān)邏輯。最后創(chuàng)建一個(gè)Action,并提交這個(gè)action。
首先我們來看看action,代碼就不貼了,基本上就是個(gè)容器類,用來存儲(chǔ)請(qǐng)求的一些信息,并且是個(gè)抽象類。需要注意的是對(duì)target的保存,使用的是弱引用,為了不造成內(nèi)存泄露。這個(gè)target就是要顯示圖片的view。action的子類承擔(dān)的工作都是下載圖片等,需要覆蓋幾個(gè)抽象方法來處理完成(設(shè)置view圖像)、錯(cuò)誤和取消等情況。那么幾乎可以肯定大部分的真正的走網(wǎng)處理都在picasso.enqueueAndSubmit(action);里面了。這里回顧下,這種設(shè)計(jì)方式將請(qǐng)求作為了一連串的參數(shù)數(shù)據(jù)保存在action里,執(zhí)行在另外的地方做,就是一個(gè)基本的數(shù)據(jù)與邏輯的分離,解耦。能夠?qū)⑦壿嫷奶幚順?biāo)準(zhǔn)化,而數(shù)據(jù)的樣式可以隨著擴(kuò)展多樣化。
下面繼續(xù)看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,那么這個(gè)submit做了什么呢?

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

到達(dá)這里,進(jìn)入了Dispatcher,Dispatcher在build的初始化階段就建立好了,是進(jìn)行action派發(fā)的機(jī)構(gòu)。

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

利用handler將action發(fā)送了出去,那么看看handler,是個(gè)DispatcherHandler,里面的最重要的handleMessage,根據(jù)參數(shù)不同做出了相關(guān)處理:

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

這個(gè)dispatcher就是Dispatcher的引用,實(shí)際上最后還是在調(diào)用Dispatcher,但為什么繞這個(gè)圈呢?原因在于:

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

看到了吧,這里用了DispatcherThread(HandlerThread的子類),并且將looper傳遞給了DispatcherHandler。也就是說,DispatcherHandler的處理過程運(yùn)行在了其他線程里,作為異步操作了,包括調(diào)用的Dispatcher的dispatcher.performSubmit(action);等方法都是如此。這里巧妙的運(yùn)用了DispatcherThread實(shí)現(xiàn)了異步線程操作,避免了ui線程的等待。那么HandlerThread是什么呢?簡單的講就是帶有消息循環(huán)looper的線程,會(huì)不斷的處理消息。那么這么分離使action的處理都獨(dú)立到了線程中。
下面來看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.是否該請(qǐng)求被暫停,如果是放入暫停action的map里;
2.從hunterMap中查找是否已經(jīng)有相同uri的BitmapHunter,如果有合并返回;
3.通過forRequest創(chuàng)建hunter;
4.提交線程池,并加入hunterMap中;
重點(diǎn)在于forRequest和提交線程池。先看下forRequest:

static BitmapHunter forRequest(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats,
      Action action) {
    Request request = action.getRequest();
    List 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.根據(jù)request依次到requestHandlers中的每個(gè)requestHandler判斷是否可處理(還記得requestHandlers一共默認(rèn)有7個(gè),還可擴(kuò)展);
3.如果可被一個(gè)requestHandler處理,則new出BitmapHunter,并傳遞這個(gè)requestHandler進(jìn)入;
這里的處理方式是個(gè)標(biāo)準(zhǔn)的鏈?zhǔn)剑来卧儐柮總€(gè)處理者是否可以,可以交付,不可以繼續(xù)。非常適合少量的處理者,并且請(qǐng)求和處理者是一對(duì)一關(guān)系的情況。

下面回來看線程池,service.submit(hunter);,這個(gè)BitmapHunter是個(gè)runnable,提交后就會(huì)在線程池分配的線程中運(yùn)行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,是個(gè)ThreadLocal對(duì)象,就是會(huì)為每個(gè)線程分離出一個(gè)對(duì)象,防止并發(fā)線程改寫該對(duì)象造成的數(shù)據(jù)錯(cuò)亂,具體概念不說了,可以具體查查看。
2.調(diào)用hunt方法返回結(jié)果,重點(diǎn),一會(huì)兒看;
3.調(diào)用dispatcher.dispatchComplete(this);或dispatcher.dispatchFailed(this);進(jìn)行收尾的處理;
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.根據(jù)策略檢查是否可直接從內(nèi)存中獲取,如果可以加載并返回;
2.通過requestHandler.load(data, networkPolicy);去獲取返回?cái)?shù)據(jù)。重點(diǎn);
3.根據(jù)之前設(shè)置的參數(shù)處理Transformation;

從requestHandler.load看起,requestHandler是個(gè)抽象類,那么我們就從NetworkRequestHandler這個(gè)比較常用的子類看起,看他的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進(jìn)行了下載活動(dòng),重點(diǎn);
2.根據(jù)response.cached確定從磁盤或網(wǎng)絡(luò)加載;
3.如果是網(wǎng)絡(luò)加載,需要走dispatchDownloadFinished,里面發(fā)送了DOWNLOAD_FINISHED請(qǐng)求,告知下載完成;

下面進(jìn)入到downloader了,Downloader又是個(gè)抽象類,實(shí)現(xiàn)有3個(gè),OkHttp3Downloader、OkHttpDownloader、UrlConnectionDownloader。默認(rèn)>9以上使用OkHttp3Downloader,備用使用OkHttpDownloader,都不行使用UrlConnectionDownloader。我們以O(shè)kHttp3Downloader為例看看:

@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.檢查網(wǎng)絡(luò)策略,如果需要從緩存里拿;
2.標(biāo)準(zhǔn)的okhttp使用下載圖片;

最后回來看下Dispatcher的dispatchComplete方法,會(huì)給ThreadHandler發(fā)送HUNTER_COMPLETE消息,而在handleMessage里面會(huì)最終走到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);內(nèi)部是延遲發(fā)送了一個(gè)HUNTER_DELAY_NEXT_BATCH消息;
在handlehandleMessage里面走的是dispatcher.performBatchComplete();注意到此為止都在異步線程中運(yùn)作。看看這個(gè)函數(shù):

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

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

case HUNTER_BATCH_COMPLETE: {
          @SuppressWarnings("unchecked") List batch = (List) 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方法中,這里實(shí)際上處理了完成的hunter。complete的關(guān)鍵就是一句話:deliverAction調(diào)用,而這里的關(guān)鍵是action.complete(result, from);一個(gè)抽象方法,最后看看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!
%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();
   }
 }

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

寫在最后

參數(shù)的設(shè)置過程和分類很好,除了主線程外,起了一個(gè)線程用來處理dispicher,沒有使用并發(fā),而是使用looper線程,后面采用線程池進(jìn)行下載的操作。各個(gè)環(huán)節(jié)擴(kuò)展性都很好,action/requesthander/downloader等。有興趣的可以再看看這里的LruCache,對(duì)LinkedHashMap的使用也是不錯(cuò)的。

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/64845.html

相關(guān)文章

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<