国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

Picasso源碼揭秘

k00baa / 1068人閱讀

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

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方法:

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的構造:

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,默認提供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:

@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的消息。這個線程就是一個垃圾回收的線程。
至此,初始化的過程結束了。

參數設置

隨便看下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 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 copy = new ArrayList(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 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方法中,這里實際上處理了完成的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!
%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的使用也是不錯的。

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/64845.html

相關文章

發表評論

0條評論

k00baa

|高級講師

TA的文章

閱讀更多
最新活動
閱讀需要支付1元查看
<