Glide你需要知道的事(源码解析)

目录

 

前言:

Picasso、Fresco、Glide:

Picasso与Glide对比

Fresco与Glide对比

小结

Glide原理解析

1.缓存原理

小结1

2.生命周期处理

小结2

总结


前言:

项目中经常用到Glide、面试也有被问到,是时候系统的深入了解一下Glide了。


Picasso、Fresco、Glide:

做Android开发的,对上述图片加载框架,应该比较熟悉了,我简单的介绍一下,对比分析一下。

Picasso是Square公司开源的项目,功能强大、调用简单:

Picasso
    .with(context)
    .load(Url)
    .into(targetImageView);

Glide是谷歌员工开源的一个项目,调用方式如下:

Glide
    .with(context)
    .load(Url)
    .into(targetImageView);

Picasso与Glide对比

从上面可以看出,二者的调用方式几乎相同,有着近乎一样的API风格,但Glide在缓存策略和加载GIF方面略胜一筹。主要区别如下:

1.调用方式上:Glide with接收的参数不仅仅是context,还可以是Activity、Fragment,并且和Activity、Fragment生命周期保持一致,在Pasuse,暂停加载图片,Resume的时候,恢复加载(后面重点介绍)。

2.磁盘缓存和图片格式:Picasso使用的是全尺寸缓存,Glide和使用的ImageView大小相同,相比来说,Glide加载图片较Picasso要快,Picasso加载前需要重新调整大小,Picasso默认使用的图片格式是ARGB8888,Glide默认使用的图片格式是RGB565,后者要比前者相同情况下,少一半内存。

3.支持GIF:Glide支持加载GIF动图、Picasso不支持。

4.包大小:Glide要比Picasso大一些。

Fresco是Facebook开源的图片库,和Glide具备相同的功能(支持加载gif)。

Fresco与Glide对比

Fresco最大的亮点在于它的内存管理,Android 解压后的图片即Android中的Bitmap,占用大量的内存,Android 5.0以下系统,会显著的引发界面卡顿,Freco很好的解决了这个问题。Fresco和Glide主要区别如下:

1.Glide加载速度快(缓存的图片规格多),内存开销小(rgb565)。

2.Fresco最大的优势在于5.0(Android 2.3)以下bitmap的加载,5.0以下系统,Fresco将图片放在一个特别的内存区域,大大减少OOM。

3.Fresco包比较大,使用麻烦,适合高性能加载大量图片。

小结

1.Picasso所能实现的功能,Glide都能实现,只是设置不同,二者区别是Picasso包体积比Glide小且图片质量比Glide高,但Glide加载速度比Picasso快,Glide支持gif,适合处理大型图片流,如果视频类应用,首选Glide。

2.Fresco综合之前图片加载库的优点,在5.0以下内存优化比较好,但包体积比较大,Fresco>Glide>Picasso,Fresco在图片较多的应用凸显其价值,但如果应用对图片需求较少的,不推荐使用。


Glide原理解析

这里我只分析Glide的缓存原理和生命周期处理。不知道大家怎么学习的,在使用了大量的框架的时候,我发现要学习一个东西,大概一个步骤就是,这个东西是什么,用来干什么,使用、熟练使用,了解原理,最后融会贯通。其实分析源码的过程,最简单的就是从调用方式出发,一步一步往下看,基本就能了解个大概,刚开始看的时候,有点吃力,多看几遍就ok了。话不多说,接下来分两个部分介绍:

1.缓存原理

2.生命周期处理

以下源码基于:glide:4.6.1

温馨提示:原理代码分析过程较长,如果不想看的话,可直接跳转到小结1、小结2。

1.缓存原理

在前面Glide和Picasso对比介绍的时候,我们已经描述了Glide最基本调用过程:

Glide
    .with(context)
    .load(Url)
    .into(targetImageView);

从上述代码可以看出,with传人的是context上下文,load加载图片资源resouce,into是设置到具体的Imageview处理显示,根据以往经验,into应该是加载图片的起点,我们先看里面的源码。

点进去发现有几个构造重载方法,随便点击去一个,我们会发现最终调用的方法是下面这个方法:

  private <Y extends Target<TranscodeType>> Y into(
      @NonNull Y target,
      @Nullable RequestListener<TranscodeType> targetListener,
      @NonNull RequestOptions options) {
    // 是否在主线程
    Util.assertMainThread();
   // 判断加载图片target是否为空
    Preconditions.checkNotNull(target);
   // 没有设置图片资源报错
    if (!isModelSet) {
      throw new IllegalArgumentException("You must call #load() before calling #into()");
    }
    // 图片资源格式clone
    options = options.autoClone();
    // 构造图片请求request
    Request request = buildRequest(target, targetListener, options);
    // 获取当前request
    Request previous = target.getRequest();
    // 新创建的request和当前相同,将新构造的request回收并复用当前request
    if (request.isEquivalentTo(previous)
        && !isSkipMemoryCacheWithCompletePreviousRequest(options, previous)) {
      request.recycle();
      // If the request is completed, beginning again will ensure the result is re-delivered,
      // triggering RequestListeners and Targets. If the request is failed, beginning again will
      // restart the request, giving it another chance to complete. If the request is already
      // running, we can let it continue running without interruption.
      // 如果当前request正在运行,直接开始加载图片
      if (!Preconditions.checkNotNull(previous).isRunning()) {
        // Use the previous request rather than the new one to allow for optimizations like skipping
        // setting placeholders, tracking and un-tracking Targets, and obtaining View dimensions
        // that are done in the individual Request.
        previous.begin();
      }
      return target;
    }
    // 清除当前request
    requestManager.clear(target);
    // 将新构造的请求和当前target绑定起来
    target.setRequest(request);
    // 开始处理新构造的request
    requestManager.track(target, request);

    return target;
  }

从上面的源码可以看出,当我们into加载图片首先会构造一个新的图片request,我们看下buildRequest(target, targetListener, options)这个方法做了那些处理,我们跟进去会发现,最终调用的是buildRequestRecursive()方法。

  private Request buildRequestRecursive(
      Target<TranscodeType> target,
      @Nullable RequestListener<TranscodeType> targetListener,
      @Nullable RequestCoordinator parentCoordinator,
      TransitionOptions<?, ? super TranscodeType> transitionOptions,
      Priority priority,
      int overrideWidth,
      int overrideHeight,
      RequestOptions requestOptions) {

    // Build the ErrorRequestCoordinator first if necessary so we can update parentCoordinator.
    // 创建一个错误处理器,以便后面可以更新原来的parentCoordinator
    ErrorRequestCoordinator errorRequestCoordinator = null;
    if (errorBuilder != null) {
      errorRequestCoordinator = new ErrorRequestCoordinator(parentCoordinator);
      parentCoordinator = errorRequestCoordinator;
    }
    // 构造一个mainRequest
    Request mainRequest =
        buildThumbnailRequestRecursive(
            target,
            targetListener,
            parentCoordinator,
            transitionOptions,
            priority,
            overrideWidth,
            overrideHeight,
            requestOptions);
    // 之前传入的parentCoordinator == null 直接返回构造的request
    if (errorRequestCoordinator == null) {
      return mainRequest;
    }
    
    // 为errorRequest图片宽、高赋值,为后续请求准备
    int errorOverrideWidth = errorBuilder.requestOptions.getOverrideWidth();
    int errorOverrideHeight = errorBuilder.requestOptions.getOverrideHeight();
    if (Util.isValidDimensions(overrideWidth, overrideHeight)
        && !errorBuilder.requestOptions.isValidOverride()) {
      errorOverrideWidth = requestOptions.getOverrideWidth();
      errorOverrideHeight = requestOptions.getOverrideHeight();
    }
    // 构造一个errorRequest,并返回
    Request errorRequest = errorBuilder.buildRequestRecursive(
        target,
        targetListener,
        errorRequestCoordinator,
        errorBuilder.transitionOptions,
        errorBuilder.requestOptions.getPriority(),
        errorOverrideWidth,
        errorOverrideHeight,
        errorBuilder.requestOptions);
    errorRequestCoordinator.setRequests(mainRequest, errorRequest);
    return errorRequestCoordinator;
  }

从上面代码可以看出,他首先会创建一个ErrorRequestCoordinator调度器,来更新之前传入的parentCoordinator,之前传入的代码如下:

return buildRequestRecursive(
        target,
        targetListener,
        /*parentCoordinator=*/ null,
        transitionOptions,
        requestOptions.getPriority(),
        requestOptions.getOverrideWidth(),
        requestOptions.getOverrideHeight(),
        requestOptions);

可以看出直接传入了一个null,所以errorRequestCoordinator = null,直接返回mainRequest;我们再一下mainRequest如何创建的:

  private Request buildThumbnailRequestRecursive(
      Target<TranscodeType> target,
      RequestListener<TranscodeType> targetListener,
      @Nullable RequestCoordinator parentCoordinator,
      TransitionOptions<?, ? super TranscodeType> transitionOptions,
      Priority priority,
      int overrideWidth,
      int overrideHeight,
      RequestOptions requestOptions) {
    if (thumbnailBuilder != null) {
      // Recursive case: contains a potentially recursive thumbnail request builder.
      ...

      ThumbnailRequestCoordinator coordinator = new ThumbnailRequestCoordinator(parentCoordinator);
      Request fullRequest =
          obtainRequest(
              target,
              targetListener,
              requestOptions,
              coordinator,
              transitionOptions,
              priority,
              overrideWidth,
              overrideHeight);
      isThumbnailBuilt = true;
      // Recursively generate thumbnail requests.
      Request thumbRequest =
          thumbnailBuilder.buildRequestRecursive(
              target,
              targetListener,
              coordinator,
              thumbTransitionOptions,
              thumbPriority,
              thumbOverrideWidth,
              thumbOverrideHeight,
              thumbnailBuilder.requestOptions);
      isThumbnailBuilt = false;
      coordinator.setRequests(fullRequest, thumbRequest);
      return coordinator;
    } else if (thumbSizeMultiplier != null) {
      // Base case: thumbnail multiplier generates a thumbnail request, but cannot recurse.
      ThumbnailRequestCoordinator coordinator = new ThumbnailRequestCoordinator(parentCoordinator);
      Request fullRequest =
          obtainRequest(
              target,
              targetListener,
              requestOptions,
              coordinator,
              transitionOptions,
              priority,
              overrideWidth,
              overrideHeight);
      RequestOptions thumbnailOptions = requestOptions.clone()
          .sizeMultiplier(thumbSizeMultiplier);

      Request thumbnailRequest =
          obtainRequest(
              target,
              targetListener,
              thumbnailOptions,
              coordinator,
              transitionOptions,
              getThumbnailPriority(priority),
              overrideWidth,
              overrideHeight);

      coordinator.setRequests(fullRequest, thumbnailRequest);
      return coordinator;
    } else {
      // Base case: no thumbnail.
      return obtainRequest(
          target,
          targetListener,
          requestOptions,
          parentCoordinator,
          transitionOptions,
          priority,
          overrideWidth,
          overrideHeight);
    }
  }

从上面代码可以看出,它分为三种请求,一种包含缩略图的请求但是递归调用的,一种包含缩略图请求直接请求的,一种不含缩略图的请求,但是他们三个最终调用了SingleRequest.obtain()方法:

   return SingleRequest.obtain(
        context,
        glideContext,
        model,
        transcodeClass,
        requestOptions,
        overrideWidth,
        overrideHeight,
        priority,
        target,
        targetListener,
        requestListener,
        requestCoordinator,
        glideContext.getEngine(),
        transitionOptions.getTransitionFactory());
  }

再往里看就是一个init方法,对请求各种参数的初始化:

 private void init(
      Context context,
      GlideContext glideContext,
      Object model,
      Class<R> transcodeClass,
      RequestOptions requestOptions,
      int overrideWidth,
      int overrideHeight,
      Priority priority,
      Target<R> target,
      RequestListener<R> targetListener,
      RequestListener<R> requestListener,
      RequestCoordinator requestCoordinator,
      Engine engine,
      TransitionFactory<? super R> animationFactory) {
    this.context = context;
    this.glideContext = glideContext;
    this.model = model;
    this.transcodeClass = transcodeClass;
    this.requestOptions = requestOptions;
    this.overrideWidth = overrideWidth;
    this.overrideHeight = overrideHeight;
    this.priority = priority;
    this.target = target;
    this.targetListener = targetListener;
    this.requestListener = requestListener;
    this.requestCoordinator = requestCoordinator;
    this.engine = engine;
    this.animationFactory = animationFactory;
    status = Status.PENDING;
  }

分析到这里我们发现,request请求构造完毕,接下来何时开始请求的呢?

我们回到最前面的into()方法里面,接着往下看,我们会发现,有两处地方,一处是previous.begin(),一处是requestManager.track(target, request),前者是复用上一个请求直接开始请求,后者是调用了RequestTracker.runRequest()方法:

  public void runRequest(@NonNull Request request) {
    requests.add(request);
    if (!isPaused) {
      request.begin();
    } else {
      pendingRequests.add(request);
    }
  }

首先将request添加到一个队列里面,如果当前不是pause状态,开始请求,否则加入待请求队列。(这里的队列不是说存储结构是队列)。

请求开始的地方找到了,我们之前构造请求分析到最终调用SingleRequest.init()方法,SingleRequest是request接口实现类,request.begin(),其实最终会回调SingleRequest.begin()方法:

  public void begin() {
    ...
    // 图片资源为空抛异常
    if (model == null) {
      if (Util.isValidDimensions(overrideWidth, overrideHeight)) {
        width = overrideWidth;
        height = overrideHeight;
      }
      // Only log at more verbose log levels if the user has set a fallback drawable, because
      // fallback Drawables indicate the user expects null models occasionally.
      int logLevel = getFallbackDrawable() == null ? Log.WARN : Log.DEBUG;
      onLoadFailed(new GlideException("Received null model"), logLevel);
      return;
    }

    if (status == Status.RUNNING) {
      throw new IllegalArgumentException("Cannot restart a running request");
    }

    // If we're restarted after we're complete (usually via something like a notifyDataSetChanged
    // that starts an identical request into the same Target or View), we can simply use the
    // resource and size we retrieved the last time around and skip obtaining a new size, starting a
    // new load etc. This does mean that users who want to restart a load because they expect that
    // the view size has changed will need to explicitly clear the View or Target before starting
    // the new load.
    // 图片加载完成,释放资源
    if (status == Status.COMPLETE) {
      onResourceReady(resource, DataSource.MEMORY_CACHE);
      return;
    }

    // Restarts for requests that are neither complete nor running can be treated as new requests
    // and can run again from the beginning.
    // 新的请求从获取图片size开始
    status = Status.WAITING_FOR_SIZE;
    if (Util.isValidDimensions(overrideWidth, overrideHeight)) {
      onSizeReady(overrideWidth, overrideHeight);
    } else {
      target.getSize(this);
    }
    // 通知加载图片开始
    if ((status == Status.RUNNING || status == Status.WAITING_FOR_SIZE)
        && canNotifyStatusChanged()) {
      target.onLoadStarted(getPlaceholderDrawable());
    }
    if (IS_VERBOSE_LOGGABLE) {
      logV("finished run method in " + LogTime.getElapsedMillis(startTime));
    }
  }

我们看上面代码会发现,一个新的请求是从onSizeReady()开始的:

public void onSizeReady(int width, int height) {
    ...
    
    loadStatus = engine.load(
        glideContext,
        model,
        requestOptions.getSignature(),
        this.width,
        this.height,
        requestOptions.getResourceClass(),
        transcodeClass,
        priority,
        requestOptions.getDiskCacheStrategy(),
        requestOptions.getTransformations(),
        requestOptions.isTransformationRequired(),
        requestOptions.isScaleOnlyOrNoTransform(),
        requestOptions.getOptions(),
        requestOptions.isMemoryCacheable(),
        requestOptions.getUseUnlimitedSourceGeneratorsPool(),
        requestOptions.getUseAnimationPool(),
        requestOptions.getOnlyRetrieveFromCache(),
        this);

    // This is a hack that's only useful for testing right now where loads complete synchronously
    // even though under any executor running on any thread but the main thread, the load would
    // have completed asynchronously.
    if (status != Status.RUNNING) {
      loadStatus = null;
    }
    if (IS_VERBOSE_LOGGABLE) {
      logV("finished onSizeReady in " + LogTime.getElapsedMillis(startTime));
    }
  }

我们看里面会调用一个engine.load()方法,engine干嘛的呢,我们进入Engine这个类,可以看到注释描述是负责加载图片和管理缓存的,我们接下来看一下这个load()方法具体实现:

  public <R> LoadStatus load(
      GlideContext glideContext,
      Object model,
      Key signature,
      int width,
      int height,
      Class<?> resourceClass,
      Class<R> transcodeClass,
      Priority priority,
      DiskCacheStrategy diskCacheStrategy,
      Map<Class<?>, Transformation<?>> transformations,
      boolean isTransformationRequired,
      boolean isScaleOnlyOrNoTransform,
      Options options,
      boolean isMemoryCacheable,
      boolean useUnlimitedSourceExecutorPool,
      boolean useAnimationPool,
      boolean onlyRetrieveFromCache,
      ResourceCallback cb) {
    Util.assertMainThread();
    long startTime = LogTime.getLogTime();

    // 生成缓存的key
    EngineKey key = keyFactory.buildKey(model, signature, width, height, transformations,
        resourceClass, transcodeClass, options);
    // 从活动缓存获取
    EngineResource<?> active = loadFromActiveResources(key, isMemoryCacheable);
    if (active != null) {
      cb.onResourceReady(active, DataSource.MEMORY_CACHE);
      if (Log.isLoggable(TAG, Log.VERBOSE)) {
        logWithTimeAndKey("Loaded resource from active resources", startTime, key);
      }
      return null;
    }
    // 从内存缓存LruCache获取
    EngineResource<?> cached = loadFromCache(key, isMemoryCacheable);
    if (cached != null) {
      cb.onResourceReady(cached, DataSource.MEMORY_CACHE);
      if (Log.isLoggable(TAG, Log.VERBOSE)) {
        logWithTimeAndKey("Loaded resource from cache", startTime, key);
      }
      return null;
    }
    // 开启线程从磁盘获取缓存
    EngineJob<?> current = jobs.get(key, onlyRetrieveFromCache);
    if (current != null) {
      current.addCallback(cb);
      if (Log.isLoggable(TAG, Log.VERBOSE)) {
        logWithTimeAndKey("Added to existing load", startTime, key);
      }
      return new LoadStatus(cb, current);
    }

    EngineJob<R> engineJob =
        engineJobFactory.build(
            key,
            isMemoryCacheable,
            useUnlimitedSourceExecutorPool,
            useAnimationPool,
            onlyRetrieveFromCache);

    DecodeJob<R> decodeJob =
        decodeJobFactory.build(
            glideContext,
            model,
            key,
            signature,
            width,
            height,
            resourceClass,
            transcodeClass,
            priority,
            diskCacheStrategy,
            transformations,
            isTransformationRequired,
            isScaleOnlyOrNoTransform,
            onlyRetrieveFromCache,
            options,
            engineJob);

    jobs.put(key, engineJob);
    // 添加加载失败、完成的回调
    engineJob.addCallback(cb);
    // 通过线程池开启一个线程
    engineJob.start(decodeJob);

    if (Log.isLoggable(TAG, Log.VERBOSE)) {
      logWithTimeAndKey("Started new load", startTime, key);
    }
    return new LoadStatus(cb, engineJob);
  }

看到这里我们会惊喜的发现有两个方法loadFromActiveResources()、loadFromCache(),这不就是我们想要获取缓存的方法吗。我们先看loadFromActiveResources()方法:

  private EngineResource<?> loadFromActiveResources(Key key, boolean isMemoryCacheable) {
    // 不使用内存缓存直接返回null
    if (!isMemoryCacheable) {
      return null;
    }
    // 通过key取出缓存
    EngineResource<?> active = activeResources.get(key);
    if (active != null) {
      // 引用计数+1
      active.acquire();
    }

    return active;
  }

我们从上面可以看到两个方法一个获取缓存的get()方法,一个是acquire()方法,分别看下实现:

 EngineResource<?> get(Key key) {
    ResourceWeakReference activeRef = activeEngineResources.get(key);
    if (activeRef == null) {
      return null;
    }

    EngineResource<?> active = activeRef.get();
    if (active == null) {
      cleanupActiveReference(activeRef);
    }
    return active;
  }

  void acquire() {
    if (isRecycled) {
      throw new IllegalStateException("Cannot acquire a recycled resource");
    }
    if (!Looper.getMainLooper().equals(Looper.myLooper())) {
      throw new IllegalThreadStateException("Must call acquire on the main thread");
    }
    ++acquired;
  }

我们从上面代码可以看出我们使用一个弱引用存储我们的活动缓存,然后用一个计数器来标记是否正在使用,每引用一次+1,相反release时候-1,最后acquired=0时,回收我们的活动缓存。

  void release() {
    if (acquired <= 0) {
      throw new IllegalStateException("Cannot release a recycled or not yet acquired resource");
    }
    if (!Looper.getMainLooper().equals(Looper.myLooper())) {
      throw new IllegalThreadStateException("Must call release on the main thread");
    }
    if (--acquired == 0) {
      listener.onResourceReleased(key, this);
    }
  }

接下来我们看一下loadFromCache()方法,如下:

  private EngineResource<?> loadFromCache(Key key, boolean isMemoryCacheable) {
    if (!isMemoryCacheable) {
      return null;
    }
    // 从Lrucahe取出缓存,并从中移除
    EngineResource<?> cached = getEngineResourceFromCache(key);
    // 将缓存存入弱引用中
    if (cached != null) {
      cached.acquire();
      activeResources.activate(key, cached);
    }
    return cached;
  }

  private EngineResource<?> getEngineResourceFromCache(Key key) {
    Resource<?> cached = cache.remove(key);

    final EngineResource<?> result;
    if (cached == null) {
      result = null;
    } else if (cached instanceof EngineResource) {
      // Save an object allocation if we've cached an EngineResource (the typical case).
      result = (EngineResource<?>) cached;
    } else {
      result = new EngineResource<>(cached, true /*isMemoryCacheable*/, true /*isRecyclable*/);
    }
    return result;
  }

  void activate(Key key, EngineResource<?> resource) {
    ResourceWeakReference toPut =
        new ResourceWeakReference(
            key,
            resource,
            getReferenceQueue(),
            isActiveResourceRetentionAllowed);

    ResourceWeakReference removed = activeEngineResources.put(key, toPut);
    if (removed != null) {
      removed.reset();
    }
  }

我们可以看到他是先从LruCache获取缓存并从Lrucache中移除,然后在放入弱引用中保存,完成缓存从LruCache到弱引用的转移。

接着engine.load()方法往下看,我们可以看到分别创建了一个EngineJob、DecodeJob,EngineJob是负责管理加载成功、失败的回调,DecodeJob是一个线程,负责获取磁盘缓存。

Engine#load方法:    engineJob.addCallback(cb);
             engineJob.start(decodeJob);
  
// 添加加载完成的回调
void addCallback(ResourceCallback cb) {
    Util.assertMainThread();
    stateVerifier.throwIfRecycled();
    if (hasResource) {
      cb.onResourceReady(engineResource, dataSource);
    } else if (hasLoadFailed) {
      cb.onLoadFailed(exception);
    } else {
      cbs.add(cb);
    }
  }
  // 开启一个线程
  public void start(DecodeJob<R> decodeJob) {
    this.decodeJob = decodeJob;
    GlideExecutor executor = decodeJob.willDecodeFromCache()
        ? diskCacheExecutor
        : getActiveSourceExecutor();
    executor.execute(decodeJob);
  }


我们知道一个线程开启后,运行的方法是run(),so我们看看DecodeJob的run()方法

  public void run() {
 
    DataFetcher<?> localFetcher = currentFetcher;
    try {
      // 如果取消了,直接通知错误
      if (isCancelled) {
        notifyFailed();
        return;
      }
      // 根据策略加载不同的缓存
      runWrapped();
    } catch (Throwable t) {

      if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "DecodeJob threw unexpectedly"
            + ", isCancelled: " + isCancelled
            + ", stage: " + stage, t);
      }
      // When we're encoding we've already notified our callback and it isn't safe to do so again.
      if (stage != Stage.ENCODE) {
        throwables.add(t);
        notifyFailed();
      }
      if (!isCancelled) {
        throw t;
      }
    } finally {
      // 最后调用clean方法
      if (localFetcher != null) {
        localFetcher.cleanup();
      }
      TraceCompat.endSection();
    }
  }

从上面的代码可以看出主要是调用了runWrapped()方法,这个方法主要是根据不同的策略加载不同类型的磁盘缓存,在分析代码之前我们先回顾一下Glide支持哪几种磁盘缓存?

Glide5大磁盘缓存策略
DiskCacheStrategy.DATA: 只缓存原始图片;
DiskCacheStrategy.RESOURCE:只缓存转换过后的图片;
DiskCacheStrategy.ALL:既缓存原始图片,也缓存转换过后的图片;对于远程图片,缓存 DATARESOURCE;对于本地图片,只缓存 RESOURCE
DiskCacheStrategy.NONE:不缓存任何内容;
DiskCacheStrategy.AUTOMATIC:默认策略,尝试对本地和远程图片使用最佳的策略。当下载网络图片时,使用DATA;对于本地图片,使用RESOURCE

从上面可以知道,Glide支持5种磁盘缓存策略,接着看runWrapped()方法实现:

  private void runWrapped() {
    switch (runReason) {
      case INITIALIZE:
        stage = getNextStage(Stage.INITIALIZE);
        currentGenerator = getNextGenerator();
        runGenerators();
        break;
      case SWITCH_TO_SOURCE_SERVICE:
        runGenerators();
        break;
      case DECODE_DATA:
        decodeFromRetrievedData();
        break;
      default:
        throw new IllegalStateException("Unrecognized run reason: " + runReason);
    }
  }

我们从上面代码可以看出主要调用了3个方法 getNextStage()、getNextGenerator()、runGenerators():

  private Stage getNextStage(Stage current) {
    switch (current) {
      case INITIALIZE:
        return diskCacheStrategy.decodeCachedResource()
            ? Stage.RESOURCE_CACHE : getNextStage(Stage.RESOURCE_CACHE);
      case RESOURCE_CACHE:
        return diskCacheStrategy.decodeCachedData()
            ? Stage.DATA_CACHE : getNextStage(Stage.DATA_CACHE);
      case DATA_CACHE:
        // Skip loading from source if the user opted to only retrieve the resource from cache.
        return onlyRetrieveFromCache ? Stage.FINISHED : Stage.SOURCE;
      case SOURCE:
      case FINISHED:
        return Stage.FINISHED;
      default:
        throw new IllegalArgumentException("Unrecognized stage: " + current);
    }
  }


  private DataFetcherGenerator getNextGenerator() {
    switch (stage) {
      case RESOURCE_CACHE:
        return new ResourceCacheGenerator(decodeHelper, this);
      case DATA_CACHE:
        return new DataCacheGenerator(decodeHelper, this);
      case SOURCE:
        return new SourceGenerator(decodeHelper, this);
      case FINISHED:
        return null;
      default:
        throw new IllegalStateException("Unrecognized stage: " + stage);
    }
  }


  private void runGenerators() {
    currentThread = Thread.currentThread();
    startFetchTime = LogTime.getLogTime();
    boolean isStarted = false;
    while (!isCancelled && currentGenerator != null
        && !(isStarted = currentGenerator.startNext())) {
      stage = getNextStage(stage);
      currentGenerator = getNextGenerator();

      if (stage == Stage.SOURCE) {
        reschedule();
        return;
      }
    }
    // We've run out of stages and generators, give up.
    if ((stage == Stage.FINISHED || isCancelled) && !isStarted) {
      notifyFailed();
    }
  }

依次往下看getNextStage()方法会根据当前Stage的状态返回下一个Stage状态,然后getNextGenerator()会根据当前的Stage状态返回对应的缓存生成器,然后执行runGenerators()方法,里面调用了缓存生成器的startNext()方法,循环执行getNextStage()getNextGenerator()方法,最后当前stage是Stage.SOURCE跳出当前循环。如果我们第一次从网络加载图片,由于Stage最开始状态是INITIALIZE,最终调用的是SouceGenerator,如果有磁盘缓存时,调用DataCacheGeneratorResouceCacheGenerator

  • ResourceCacheGenerator: 变换之后的数据缓存生成器。
  • DataCacheGenerator:直接从网络获取的数据缓存生成器。
  • SourceGenerator: 未经变换原始数据缓存生成器。

我们在SouceGenerator的StartNext()可以看到:

  public boolean startNext() {
    // 如果有缓存,从缓存中获取
    if (dataToCache != null) {
      Object data = dataToCache;
      dataToCache = null;
      cacheData(data);
    }
    // 调用DataCacheGenerator startNext()方法
    if (sourceCacheGenerator != null && sourceCacheGenerator.startNext()) {
      return true;
    }
    sourceCacheGenerator = null;

    loadData = null;
    boolean started = false;
    while (!started && hasNextModelLoader()) {
      loadData = helper.getLoadData().get(loadDataListIndex++);
      if (loadData != null
          && (helper.getDiskCacheStrategy().isDataCacheable(loadData.fetcher.getDataSource())
          || helper.hasLoadPath(loadData.fetcher.getDataClass()))) {
        started = true;
        // 从网络加载数据
        loadData.fetcher.loadData(helper.getPriority(), this);
      }
    }
    return started;
  }

从上面代码可以看出SouceGenerator.StartNext()方法先会判断当前是否有缓存,由于第一次从网络加载图片是没有缓存的,最终调用的是fetcher.loadData()方法,通过HttpUrlFetcher实现的,代码如下:

  @Override
  public void loadData(@NonNull Priority priority,
      @NonNull DataCallback<? super InputStream> callback) {
    long startTime = LogTime.getLogTime();
    try {
      InputStream result = loadDataWithRedirects(glideUrl.toURL(), 0, null, glideUrl.getHeaders());
      // 请求完成回调
      callback.onDataReady(result);
    } catch (IOException e) {
      if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Failed to load data for url", e);
      }
      callback.onLoadFailed(e);
    } finally {
      if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "Finished http url fetcher fetch in " + LogTime.getElapsedMillis(startTime));
      }
    }
  }

请求完成通过onDataReady()回调-->到SourceGenerator.onDataFetcherReady()方法先保存数据:

  @Override
  public void onDataReady(Object data) {
    DiskCacheStrategy diskCacheStrategy = helper.getDiskCacheStrategy();
    if (data != null && diskCacheStrategy.isDataCacheable(loadData.fetcher.getDataSource())) {
      // 保存数据
      dataToCache = data;
      // We might be being called back on someone else's thread. Before doing anything, we should
      // reschedule to get back onto Glide's thread.
      // 回调
      cb.reschedule();
    } else {
      cb.onDataFetcherReady(loadData.sourceKey, data, loadData.fetcher,
          loadData.fetcher.getDataSource(), originalKey);
    }
  }

通过回调,最终通过DecodeJob#run()方法通过decodeFromRetrievedData()方法调用notifyEncodeAndRelease()方法

  private void decodeFromRetrievedData() {
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
      logWithTimeAndKey("Retrieved data", startFetchTime,
          "data: " + currentData
              + ", cache key: " + currentSourceKey
              + ", fetcher: " + currentFetcher);
    }
    Resource<R> resource = null;
    try {
      resource = decodeFromData(currentFetcher, currentData, currentDataSource);
    } catch (GlideException e) {
      e.setLoggingDetails(currentAttemptingKey, currentDataSource);
      throwables.add(e);
    }
    if (resource != null) {
      // 加载数据
      notifyEncodeAndRelease(resource, currentDataSource);
    } else {
      runGenerators();
    }
  }

最后到handleResultOnMainThread()方法完成加载图片,并通过弱引用写入缓存:

  @Synthetic
  void handleResultOnMainThread() {
    stateVerifier.throwIfRecycled();
    if (isCancelled) {
      resource.recycle();
      release(false /*isRemovedFromQueue*/);
      return;
    } else if (cbs.isEmpty()) {
      throw new IllegalStateException("Received a resource without any callbacks to notify");
    } else if (hasResource) {
      throw new IllegalStateException("Already have resource");
    }
    engineResource = engineResourceFactory.build(resource, isCacheable);
    hasResource = true;

    // Hold on to resource for duration of request so we don't recycle it in the middle of
    // notifying if it synchronously released by one of the callbacks.
    engineResource.acquire();
    // 图片请求完成,并写入缓存
    listener.onEngineJobComplete(this, key, engineResource);

    //noinspection ForLoopReplaceableByForEach to improve perf
    for (int i = 0, size = cbs.size(); i < size; i++) {
      ResourceCallback cb = cbs.get(i);
      if (!isInIgnoredCallbacks(cb)) {
        engineResource.acquire();
        cb.onResourceReady(engineResource, dataSource);
      }
    }
    // Our request is complete, so we can release the resource.
    engineResource.release();

    release(false /*isRemovedFromQueue*/);
  }


 public void onEngineJobComplete(EngineJob<?> engineJob, Key key, EngineResource<?> resource) {
    Util.assertMainThread();
    // A null resource indicates that the load failed, usually due to an exception.
    if (resource != null) {
      resource.setResourceListener(key, this);

      if (resource.isCacheable()) {
        activeResources.activate(key, resource);
      }
    }

    jobs.removeIfCurrent(key, engineJob);
  }

我们第一次从网络加载图片是通过SouceGenerator从网络获取显示并写入缓存,我们再看看DataCacheGenerator、ResouceCacheGenerator缓存获取。

public boolean startNext() {
    List<Key> sourceIds = helper.getCacheKeys();
    if (sourceIds.isEmpty()) {
      return false;
    }
    List<Class<?>> resourceClasses = helper.getRegisteredResourceClasses();
    if (resourceClasses.isEmpty()) {
      if (File.class.equals(helper.getTranscodeClass())) {
        return false;
      }
      throw new IllegalStateException(
          "Failed to find any load path from " + helper.getModelClass() + " to "
              + helper.getTranscodeClass());
    }
    while (modelLoaders == null || !hasNextModelLoader()) {
      resourceClassIndex++;
      if (resourceClassIndex >= resourceClasses.size()) {
        sourceIdIndex++;
        if (sourceIdIndex >= sourceIds.size()) {
          return false;
        }
        resourceClassIndex = 0;
      }

      Key sourceId = sourceIds.get(sourceIdIndex);
      Class<?> resourceClass = resourceClasses.get(resourceClassIndex);
      Transformation<?> transformation = helper.getTransformation(resourceClass);
     
      // 获取缓存Key
      currentKey =
          new ResourceCacheKey(// NOPMD AvoidInstantiatingObjectsInLoops
              helper.getArrayPool(),
              sourceId,
              helper.getSignature(),
              helper.getWidth(),
              helper.getHeight(),
              transformation,
              resourceClass,
              helper.getOptions());
      // 读取缓存
      cacheFile = helper.getDiskCache().get(currentKey);
      if (cacheFile != null) {
        sourceKey = sourceId;
        modelLoaders = helper.getModelLoaders(cacheFile);
        modelLoaderIndex = 0;
      }
    }

    loadData = null;
    boolean started = false;
    while (!started && hasNextModelLoader()) {
      ModelLoader<File, ?> modelLoader = modelLoaders.get(modelLoaderIndex++);
      loadData = modelLoader.buildLoadData(cacheFile,
          helper.getWidth(), helper.getHeight(), helper.getOptions());
      if (loadData != null && helper.hasLoadPath(loadData.fetcher.getDataClass())) {
        started = true;
        // 网络加载
        loadData.fetcher.loadData(helper.getPriority(), this);
      }
    }

    return started;
  }

大概流程:先获取缓存key,然后取出缓存,如果缓存不存在,通过网络重新获取。

至此,终于将Glide缓存原理全部分析完毕,总结一下。

小结1

Glide总共有2级缓存,一级内存缓存包括弱引用活动缓存、LruCache缓存,二级DiskLruCache,第一次从网络加载图片时,会开启线程从网络下载图片,下载完成后保存到磁盘,然后再加入弱引用缓存,下次加载图片会先从弱引用获取,弱引用维护一个acquired参数,判断当前图片是否正在使用,每load一次+1,每release一次-1,如果acquired == 0时,代表图片不在使用,回收弱引用对象并把缓存写入LruCache,如果从弱引用获取不到缓存,就会从LruCache获取缓存,并将从当前队列移除,放入弱引用保存,最后如果LruCache也获取不到缓存,从磁盘获取缓存,如果磁盘缓存不存在,就会重新从网络加载图片。

2.生命周期处理

Glide生命周期相比缓存处理,要简单不少,下面通过源码简单介绍一下。

熟悉Glide的同学应该知道,Glide是通过Glide.With("xxx")传入生命周期:

大概有5个构造方法,和之前一样随便点进去一个去看:

  @NonNull
  public RequestManager get(@NonNull Context context) {
    if (context == null) {
      throw new IllegalArgumentException("You cannot start a load on a null Context");
    } else if (Util.isOnMainThread() && !(context instanceof Application)) {
      if (context instanceof FragmentActivity) {
        return get((FragmentActivity) context);
      } else if (context instanceof Activity) {
        return get((Activity) context);
      } else if (context instanceof ContextWrapper) {
        return get(((ContextWrapper) context).getBaseContext());
      }
    }

    return getApplicationManager(context);
  }

我们发现其实你传入无论是fragment还是activity还是view context主要分为两种一种是Application、一种非Application,我们先看下Application的,返回的是getApplicationManager(context):


  @NonNull
  private RequestManager getApplicationManager(@NonNull Context context) {
    // Either an application context or we're on a background thread.
    if (applicationManager == null) {
      synchronized (this) {
        if (applicationManager == null) {

          // TODO(b/27524013): Factor out this Glide.get() call.
          Glide glide = Glide.get(context.getApplicationContext());
          applicationManager =
              factory.build(
                  glide,
                  new ApplicationLifecycle(),
                  new EmptyRequestManagerTreeNode(),
                  context.getApplicationContext());
        }
      }
    }

    return applicationManager;
  }

从上面代码可以看出关联的是app生命周期,和应用的生命周期一致。我们再看非Application,根据是否support包下区分为

fragmentGet()、supportFragmentGet()方法:
  private RequestManager supportFragmentGet(@NonNull Context context, @NonNull FragmentManager fm,
      @Nullable Fragment parentHint) {
    // 创建一个空白fragment
    SupportRequestManagerFragment current = getSupportRequestManagerFragment(fm, parentHint);
    RequestManager requestManager = current.getRequestManager();
    if (requestManager == null) {
      // glide关联fragment的生命周期
      Glide glide = Glide.get(context);
      requestManager =
          factory.build(
              glide, current.getGlideLifecycle(), current.getRequestManagerTreeNode(), context);
      current.setRequestManager(requestManager);
    }
    return requestManager;
  }

  @NonNull
  private RequestManager fragmentGet(@NonNull Context context,
      @NonNull android.app.FragmentManager fm,
      @Nullable android.app.Fragment parentHint) {
    // 创建一个空白fragment
    RequestManagerFragment current = getRequestManagerFragment(fm, parentHint);
    RequestManager requestManager = current.getRequestManager();
    if (requestManager == null) {
      // TODO(b/27524013): Factor out this Glide.get() call.
      Glide glide = Glide.get(context);
     // glide关联fragment的生命周期
      requestManager =
          factory.build(
              glide, current.getGlideLifecycle(), current.getRequestManagerTreeNode(), context);
      current.setRequestManager(requestManager);
    }
    return requestManager;
  }

我们可以看到他们首先都会创建一个空白fragment,然后和Glide关联起来。

  RequestManagerFragment getRequestManagerFragment(
      @NonNull final android.app.FragmentManager fm, @Nullable android.app.Fragment parentHint) {
    // 先根据tag查找是否存在
    RequestManagerFragment current = (RequestManagerFragment) fm.findFragmentByTag(FRAGMENT_TAG);
    if (current == null) {
      如果为空从map中取出
      current = pendingRequestManagerFragments.get(fm);
      if (current == null) {
        // 创建一个空白fragment
        current = new RequestManagerFragment();
        current.setParentFragmentHint(parentHint);
        // 放入map里面
        pendingRequestManagerFragments.put(fm, current);
        // 添加之前创建的空白fragment
        fm.beginTransaction().add(current, FRAGMENT_TAG).commitAllowingStateLoss();
        // 通知map移除刚添加的fragment
        handler.obtainMessage(ID_REMOVE_FRAGMENT_MANAGER, fm).sendToTarget();
      }
    }
    return current;
  }

我们进入RequestManagerFragment会发现,创建的时候,会默认构造一个ActivityFragmentLifecycle:

  public RequestManagerFragment() {
    this(new ActivityFragmentLifecycle());
  }


class ActivityFragmentLifecycle implements Lifecycle {
 
   // 省略代码...
  @Override
  public void addListener(@NonNull LifecycleListener listener) {
    lifecycleListeners.add(listener);

    if (isDestroyed) {
      listener.onDestroy();
    } else if (isStarted) {
      listener.onStart();
    } else {
      listener.onStop();
    }
  }

  @Override
  public void removeListener(@NonNull LifecycleListener listener) {
    lifecycleListeners.remove(listener);
  }

  void onStart() {
    isStarted = true;
    for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
      lifecycleListener.onStart();
    }
  }

  void onStop() {
    isStarted = false;
    for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
      lifecycleListener.onStop();
    }
  }

  void onDestroy() {
    isDestroyed = true;
    for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
      lifecycleListener.onDestroy();
    }
  }
}

其中声明了onStart()、onStop()、onDestroy()方法,我们再看RequestManagerFragment里面对应的onStart()、onStop()、onDestroy()方法:

#RequestManagerFragment

  @Override
  public void onStart() {
    super.onStart();
    lifecycle.onStart();
  }

  @Override
  public void onStop() {
    super.onStop();
    lifecycle.onStop();
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    lifecycle.onDestroy();
    unregisterFragmentWithRoot();
  }

会发现fragment周期方法回调的时候会回调ActivityFragmentLifecycle的方法,然后遍历所有LifecycleListener,LifecycleListener是什么呢?

public interface LifecycleListener {

  /**
   * Callback for when {@link android.app.Fragment#onStart()}} or {@link
   * android.app.Activity#onStart()} is called.
   */
  void onStart();

  /**
   * Callback for when {@link android.app.Fragment#onStop()}} or {@link
   * android.app.Activity#onStop()}} is called.
   */
  void onStop();

  /**
   * Callback for when {@link android.app.Fragment#onDestroy()}} or {@link
   * android.app.Activity#onDestroy()} is called.
   */
  void onDestroy();
}

其实就是Glide定义生命周期相关接口,通过接口回调,来控制暂停、恢复加载、移除相关操作。

小结2

总结一下,Glide生命周期和Activity、Fragment关联,是通过with方法传入参数,如果是Application context就与app的生命周期关联起来,如果非Application context 先判断是否是后台线程,会转为Application context方法,继续执行,如果不是就会通过创建一个空白fragment,并构造一个ActivityFragmentLifecycle接口,fragment生命周期方法调用时,ActivityFragmentLifecycle中的接口方法会调用并回调到Glide LifecycleListener接口,从而实现了和fragment生命周期管理起来。


总结

至此,终于全部分析完了,本文描述了Glide、Fresco、Picasso对比,着重从源码分析了一下Glide缓存和生命周期原理,由于个人水平有限,有误的地方敬请指出,谢谢。

Thanks:

Android 【手撕Glide】--Glide缓存机制

创作不易,如果觉得有用的话,麻烦点个赞。

 

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值