Glide源码解析

2019-05-21  本文已影响0人  呼噜噜11

背景

Glide是android开发经常用的到的一个图片加载库,他是由Bump Technologies开源的一款图片加载库。开始研究它的源码,主要是因为在一次android的热更新结束之后,源码都改变了,但是在热更新中替换的图片确没有生效。可以确定的,通过android的adb,我们找到了热更新包在手机里面的存储地址,并且把图片拷贝出来,可以发现图片已经更新到手机里面,但是运行结果仍然是显示的之前的图片。于是,带着问题,花了几天时间,对Glide源码进行了一次系统的研究。

Glide库的使用

Glide的库的使用很简单:

Glide.with(this).load(url)
                .placeholder(R.mipmap.ic_launcher)
                .error(R.mipmap.ic_launcher)
                .centerCrop()
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                .priority(Priority.HIGH)
                .into(mIvMn);

Glide缓存机制

1.先从activeResources 获取缓存
EngineResource<?> active = loadFromActiveResources(key, isMemoryCacheable);
    if (active != null) {
      cb.onResourceReady(active, DataSource.MEMORY_CACHE);
      if (VERBOSE_IS_LOGGABLE) {
        logWithTimeAndKey("Loaded resource from active resources", startTime, key);
      }
      return null;
    }
@Nullable
  private EngineResource<?> loadFromActiveResources(Key key, boolean isMemoryCacheable) {
    if (!isMemoryCacheable) {
      return null;
    }
    EngineResource<?> active = activeResources.get(key);
    if (active != null) {
      active.acquire();
    }

    return active;
  }
2.activeResources获取失败再从Lrucahe后去缓存,其中Lrucache的实现可以参考:LruResourceCache文件
EngineResource<?> cached = loadFromCache(key, isMemoryCacheable);
    if (cached != null) {
      cb.onResourceReady(cached, DataSource.MEMORY_CACHE);
      if (VERBOSE_IS_LOGGABLE) {
        logWithTimeAndKey("Loaded resource from cache", startTime, key);
      }
      return null;
    }
private EngineResource<?> loadFromCache(Key key, boolean isMemoryCacheable) {
    if (!isMemoryCacheable) {
      return null;
    }

    EngineResource<?> cached = getEngineResourceFromCache(key);
    if (cached != null) {
      cached.acquire();
      //Lrucache获取成功后会把他加入的activeResources中
      activeResources.activate(key, cached);
    }
    return cached;
  }
1.stage状态决定从哪个地方加载图片,其中初始状态为 INITIALIZE
private enum Stage {
    /** The initial stage. */
    INITIALIZE,
    /** Decode from a cached resource. */
    RESOURCE_CACHE,
    /** Decode from cached source data. */
    DATA_CACHE,
    /** Decode from retrieved source. */
    SOURCE,
    /** Encoding transformed resources after a successful load. */
    ENCODE,
    /** No more viable stages. */
    FINISHED,
  }
2.根据stage状态决定下一个加载状态,默认状态下,也就是diskCacheStrategy.AUTOMATIC时,状态顺序为 INITIALIZE -> RESOURCE_CACHE -> DATA_CACHE -> SOURCE
  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);
    }
  }
3.获取Generator类型
  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);
    }
  }
4.run Generator,其中 currentGenerator.startNext()失败时,会返回false,直到加载到指定文件
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();
    }

    // Otherwise a generator started a new load and we expect to be called back in
    // onDataFetcherReady.
  }

总结

通过了解Glide的缓存一系列流程,对于热更新之后图片无法更新的问题也有了答案,具体原因就是因为热更细结束之后,图片的缓存其实并没有更新,虽然原图更新了,但是因为Glide加载会下去加载缓存,只有在缓存不存在的情况下才会去加载原图。因此,在不改变glide源码的情况下,对于需要热更新图片,可以通过如下方法规避:
1.如果替换图片了,最好修改图片文件名称
2.设置glide加载只读原图

上一篇下一篇

猜你喜欢

热点阅读