Android 主流开源框架(六)Glide 的执行流程源码解析

前言

最近有个想法——就是把 Android 主流开源框架进行深入分析,然后写成一系列文章,包括该框架的详细使用与源码解析。目的是通过鉴赏大神的源码来了解框架底层的原理,也就是做到不仅要知其然,还要知其所以然。

这里我说下自己阅读源码的经验,我一般都是按照平时使用某个框架或者某个系统源码的使用流程入手的,首先要知道怎么使用,然后再去深究每一步底层做了什么,用了哪些好的设计模式,为什么要这么设计。

系列文章:

更多干货请关注 AndroidNotes

一、Glide 的基本使用示例

Glide 是一个快速高效的 Android 图片加载库,也是 Google 官方推荐的图片加载库。多数情况下,使用 Glide 加载图片非常简单,一行代码就能解决。如下:

Glide.with(this).load(url).into(imageView);

这行代码用起来虽然简单,但是涉及到的三个方法 with()、load()、into() 的内部实现是比较复杂的,接下来我们就根据这三个方法进行源码阅读。这里没有单独用一篇文章来写 Glide 的使用,是因为官方文档已经非常详细了,看不懂英文的可以直接看中文的。

二、Glide 源码分析

这篇文章主要分析 Glide 的执行流程,Glide 的缓存机制在下一篇文章中分析,这两篇都是使用最新的 4.11.0 版本来分析。

因为 Glide 默认是配置了内存与磁盘缓存的,所以这里我们先禁用内存和磁盘缓存。如下设置:

Glide.with(this)
        .load(url)
        .skipMemoryCache(true) // 禁用内存缓存
        .diskCacheStrategy(DiskCacheStrategy.NONE) // 禁用磁盘缓存
        .into(imageView);

注意:后面的分析都是加了跳过缓存的,所以你在跟着本文分析的时候记得加上上面两句。

2.1 with()

with() 的重载方法有 6 个:

  • Glide#with(Context context)
  • Glide#with(Activity activity)
  • Glide#with(FragmentActivity activity)
  • Glide#with(Fragment fragment)
  • Glide#with(android.app.Fragment fragment)
  • Glide#with(View view)

这些方法的参数可以分成两种情况,即 Application(Context)类型与非 Application(Activity、Fragment、View,这里的 View 获取的是它所属的 Activity 或 Fragment)类型,这些参数的作用是确定图片加载的生命周期。点击进去发现 6 个重载方法最终都会调用 getRetriever().get(),所以这里只拿 FragmentActivity 来演示:

  /*Glide*/
  public static RequestManager with(@NonNull FragmentActivity activity) {
    return getRetriever(activity).get(activity);
  }

2.1.1 Glide#getRetriever()

点击 getRetriever() 方法进去:

  /*Glide*/
  private static RequestManagerRetriever getRetriever(@Nullable Context context) {
    ...
    return Glide.get(context).getRequestManagerRetriever();
  }

继续看下 Glide#get(context):

  /*Glide*/
  public static Glide get(@NonNull Context context) {
    if (glide == null) {
      //(1)
      GeneratedAppGlideModule annotationGeneratedModule =
          getAnnotationGeneratedGlideModules(context.getApplicationContext());
      synchronized (Glide.class) {
        if (glide == null) {
          //(2)
          checkAndInitializeGlide(context, annotationGeneratedModule);
        }
      }
    }

    return glide;
  }

这里使用了双重校验锁的单例模式来获取 Glide 的实例,其中关注点(1)点击进去看看:

  /*Glide*/
  private static GeneratedAppGlideModule getAnnotationGeneratedGlideModules(Context context) {
    GeneratedAppGlideModule result = null;
      Class<GeneratedAppGlideModule> clazz =
          (Class<GeneratedAppGlideModule>)
              Class.forName("com.bumptech.glide.GeneratedAppGlideModuleImpl");
      result =
 clazz.getDeclaredConstructor(Context.class).newInstance(context.getApplicationContext());
 
    ...
    
    return result;
  }

该方法用来实例化我们用 @GlideModule 注解标识的自定义模块,这里提一下自定义模块的用法。

  • Glide 3 用法
    定义一个类实现 GlideModule,如下:
public class MyGlideModule implements GlideModule {

    @Override
    public void applyOptions(Context context, GlideBuilder builder) {

    }

    @Override
    public void registerComponents(Context context, Glide glide) {

    }
}

其中 applyOptions() 与 registerComponents() 方法分别用来更改 Glide 的配置以及替换 Glide 组件。

然后在 AndroidManifest.xml 文件中加入如下配置:

    <application>

        ...

        <meta-data
            android:name="com.wildma.myapplication.MyGlideModule"
            android:value="GlideModule" />
    </application>
  • Glide 4 用法
    定义一个类实现 AppGlideModule,然后加上 @GlideModule 注解即可。如下:
@GlideModule
public final class MyAppGlideModule extends AppGlideModule {

    @Override
    public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
    }

    @Override
    public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
    }
}

关于 @GlideModule 的更详细使用可以查看 Generated API

接下来继续查看关注点(2):

  /*Glide*/
  private static void checkAndInitializeGlide(
      @NonNull Context context, @Nullable GeneratedAppGlideModule generatedAppGlideModule) {
    // 不能重复初始化
    if (isInitializing) {
      throw new IllegalStateException(
          "You cannot call Glide.get() in registerComponents(),"
              + " use the provided Glide instance instead");
    }
    isInitializing = true;
    initializeGlide(context, generatedAppGlideModule);
    isInitializing = false;
  }
  
    /*Glide*/
    private static void initializeGlide(
      @NonNull Context context, @Nullable GeneratedAppGlideModule generatedAppGlideModule) {
    initializeGlide(context, new GlideBuilder(), generatedAppGlideModule);
  }
  
    /*Glide*/
  private static void initializeGlide(
      @NonNull Context context,
      @NonNull GlideBuilder builder,
      @Nullable GeneratedAppGlideModule annotationGeneratedModule) {
    Context applicationContext = context.getApplicationContext();
    List<com.bumptech.glide.module.GlideModule> manifestModules = Collections.emptyList();
    if (annotationGeneratedModule == null || annotationGeneratedModule.isManifestParsingEnabled()) {
      //(1)
      manifestModules = new ManifestParser(applicationContext).parse();
    }

    ...

    // 从注解生成的 GeneratedAppGlideModule 中获取 RequestManagerFactory
    RequestManagerRetriever.RequestManagerFactory factory =
        annotationGeneratedModule != null
            ? annotationGeneratedModule.getRequestManagerFactory()
            : null;
    // 将 RequestManagerFactory 设置到 GlideBuilder
    builder.setRequestManagerFactory(factory);
    //(2)
    for (com.bumptech.glide.module.GlideModule module : manifestModules) {
      module.applyOptions(applicationContext, builder);
    }
    //(3)
    if (annotationGeneratedModule != null) {
      annotationGeneratedModule.applyOptions(applicationContext, builder);
    }
    //(4)
    Glide glide = builder.build(applicationContext);
    for (com.bumptech.glide.module.GlideModule module : manifestModules) {
      try {
        // (5)
        module.registerComponents(applicationContext, glide, glide.registry);
      } catch (AbstractMethodError e) {
        throw new IllegalStateException(
            "Attempting to register a Glide v3 module. If you see this, you or one of your"
                + " dependencies may be including Glide v3 even though you're using Glide v4."
                + " You'll need to find and remove (or update) the offending dependency."
                + " The v3 module name is: "
                + module.getClass().getName(),
            e);
      }
    }
    if (annotationGeneratedModule != null) {
      // (6)
      annotationGeneratedModule.registerComponents(applicationContext, glide, glide.registry);
    }
    // 注册组件回调
    applicationContext.registerComponentCallbacks(glide);
    //(7)
    Glide.glide = glide;
  }

可以看到,调用 checkAndInitializeGlide() 方法后最终调用了最多参数的 initializeGlide() 方法。源码中我标记了 7 个关注点,分别如下:

  • (1):将 AndroidManifest.xml 中所有值为 GlideModule 的 meta-data 配置读取出来,并将相应的自定义模块实例化。也就是实例化前面演示的在 Glide 3 中的自定义模块。

  • (2)(3):分别从两个版本的自定义模块中更改 Glide 的配置。

  • (4):使用建造者模式创建 Glide。

  • (5)(6):分别从两个版本的自定义模块中替换 Glide 组件。

  • (7):将创建的 Glide 赋值给 Glide 的静态变量。

    继续看下关注点(4)内部是如何创建 Glide 的,进入 GlideBuilder#build():

  /*GlideBuilder*/
  Glide build(@NonNull Context context) {
    if (sourceExecutor == null) {
      // 创建网络请求线程池
      sourceExecutor = GlideExecutor.newSourceExecutor();
    }

    if (diskCacheExecutor == null) {
      // 创建磁盘缓存线程池
      diskCacheExecutor = GlideExecutor.newDiskCacheExecutor();
    }

    if (animationExecutor == null) {
      // 创建动画线程池
      animationExecutor = GlideExecutor.newAnimationExecutor();
    }

    if (memorySizeCalculator == null) {
      // 创建内存大小计算器
      memorySizeCalculator = new MemorySizeCalculator.Builder(context).build();
    }

    if (connectivityMonitorFactory == null) {
      // 创建默认网络连接监视器工厂
      connectivityMonitorFactory = new DefaultConnectivityMonitorFactory();
    }

    // 创建 Bitmap 池
    if (bitmapPool == null) {
      int size = memorySizeCalculator.getBitmapPoolSize();
      if (size > 0) {
        bitmapPool = new LruBitmapPool(size);
      } else {
        bitmapPool = new BitmapPoolAdapter();
      }
    }

    if (arrayPool == null) {
      // 创建固定大小的数组池(4MB),使用 LRU 策略来保持数组池在最大字节数以下
      arrayPool = new LruArrayPool(memorySizeCalculator.getArrayPoolSizeInBytes());
    }

    if (memoryCache == null) {
      // 创建内存缓存
      memoryCache = new LruResourceCache(memorySizeCalculator.getMemoryCacheSize());
    }

    if (diskCacheFactory == null) {、
      // 创建磁盘缓存工厂
      diskCacheFactory = new InternalCacheDiskCacheFactory(context);
    }

    /*创建加载以及管理活动资源和缓存资源的引擎*/
    if (engine == null) {
      engine =
          new Engine(
              memoryCache,
              diskCacheFactory,
              diskCacheExecutor,
              sourceExecutor,
              GlideExecutor.newUnlimitedSourceExecutor(),
              animationExecutor,
              isActiveResourceRetentionAllowed);
    }

    if (defaultRequestListeners == null) {
      defaultRequestListeners = Collections.emptyList();
    } else {
      defaultRequestListeners = Collections.unmodifiableList(defaultRequestListeners);
    }

    // 创建请求管理类,这里的 requestManagerFactory 就是前面 GlideBuilder#setRequestManagerFactory() 设置进来的
    // 也就是 @GlideModule 注解中获取的
    RequestManagerRetriever requestManagerRetriever =
        new RequestManagerRetriever(requestManagerFactory);

    //(1)创建 Glide
    return new Glide(
        context,
        engine,
        memoryCache,
        bitmapPool,
        arrayPool,
        requestManagerRetriever,
        connectivityMonitorFactory,
        logLevel,
        defaultRequestOptionsFactory,
        defaultTransitionOptions,
        defaultRequestListeners,
        isLoggingRequestOriginsEnabled,
        isImageDecoderEnabledForBitmaps);
  }

可以看到,build() 方法主要是创建一些线程池、Bitmap 池、缓存策略、Engine 等,然后利用这些来创建具体的 Glide。继续看下 Glide 的构造函数:

  /*Glide*/
  Glide(...) {
    /*将传进来的参数赋值给 Glide 类中的一些常量,方便后续使用。*/
    this.engine = engine;
    this.bitmapPool = bitmapPool;
    this.arrayPool = arrayPool;
    this.memoryCache = memoryCache;
    this.requestManagerRetriever = requestManagerRetriever;
    this.connectivityMonitorFactory = connectivityMonitorFactory;
    this.defaultRequestOptionsFactory = defaultRequestOptionsFactory;

    final Resources resources = context.getResources();

    // 创建 Registry,Registry 的作用是管理组件注册,用来扩展或替换 Glide 的默认加载、解码和编码逻辑。
    registry = new Registry();
    
    // 省略的部分主要是:创建一些处理图片的解析器、解码器、转码器等,然后将他们添加到 Registry 中
    ...

    // 创建 ImageViewTargetFactory,用来给 View 获取正确类型的 ViewTarget(BitmapImageViewTarget 或 DrawableImageViewTarget)
    ImageViewTargetFactory imageViewTargetFactory = new ImageViewTargetFactory();
    // 构建一个 Glide 专属的上下文
    glideContext =
        new GlideContext(
            context,
            arrayPool,
            registry,
            imageViewTargetFactory,
            defaultRequestOptionsFactory,
            defaultTransitionOptions,
            defaultRequestListeners,
            engine,
            isLoggingRequestOriginsEnabled,
            logLevel);
  }

到这一步,Glide 才算真正创建成功。也就是 Glide.get(context).getRequestManagerRetriever() 中的 get() 方法已经走完了。

接下来看下 getRequestManagerRetriever() 方法:

    /*Glide*/
    public RequestManagerRetriever getRequestManagerRetriever() {
    return requestManagerRetriever;
  }

发现这里直接返回了实例,其实 RequestManagerRetriever 的实例在前面的 GlideBuilder#build() 方法中已经创建了,所以这里可以直接返回。

到这一步,getRetriever(activity).get(activity) 中的 getRetriever() 方法也已经走完了,并返回了 RequestManagerRetriever,接下来继续看下 get() 方法。

2.1.2 RequestManagerRetriever#get()

RequestManagerRetriever#get() 的重载方法同样有 6 个:

  • RequestManagerRetriever#get(Context context)
  • RequestManagerRetriever#get(Activity activity)
  • RequestManagerRetriever#get(FragmentActivity activity)
  • RequestManagerRetriever#get(Fragment fragment)
  • RequestManagerRetriever#get(android.app.Fragment fragment)
  • RequestManagerRetriever#get(View view)

这些方法的参数同样可以分成两种情况,即 Application 与非 Application 类型。先看下 Application 类型的情况:

  /*RequestManagerRetriever*/
  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)) {
      /*(1)*/
      if (context instanceof FragmentActivity) {
        return get((FragmentActivity) context);
      } else if (context instanceof Activity) {
        return get((Activity) context);
      } else if (context instanceof ContextWrapper
          && ((ContextWrapper) context).getBaseContext().getApplicationContext() != null) {
        return get(((ContextWrapper) context).getBaseContext());
      }
    }

    //(2)
    return getApplicationManager(context);
  }

这里标注了 2 个关注点,分别如下:

  • (1):判断如果当前线程是在主线程,并且 context 不属于 Application 类型,那么会走对应重载方法。
  • (2):属于 Application 类型,就会调用 getApplicationManager(context) 方法,点进去看看:
  /*RequestManagerRetriever*/
  private RequestManager getApplicationManager(@NonNull Context context) {
    if (applicationManager == null) {
      synchronized (this) {
        if (applicationManager == null) {
          Glide glide = Glide.get(context.getApplicationContext());
          applicationManager =
              factory.build(
                  glide,
                  new ApplicationLifecycle(),
                  new EmptyRequestManagerTreeNode(),
                  context.getApplicationContext());
        }
      }
    }

    return applicationManager;
  }

可以看到,这里使用了单例模式来获取 RequestManager,里面重新用 Application 类型的 Context 来获取 Glide 的实例。这里并没有专门做生命周期的处理,
因为 Application 对象的生命周期即为应用程序的生命周期,所以在这里图片请求的生命周期是和应用程序同步的。

我们继续看下非 Application 类型的情况,这里只拿 FragmentActivity 来讲,其他类似。代码如下:

  /*RequestManagerRetriever*/
  public RequestManager get(@NonNull FragmentActivity activity) {
    if (Util.isOnBackgroundThread()) {
      return get(activity.getApplicationContext());
    } else {
      // 检查 Activity 是否销毁
      assertNotDestroyed(activity);
      // 获取当前 Activity 的 FragmentManager
      FragmentManager fm = activity.getSupportFragmentManager();
      return supportFragmentGet(activity, fm, /*parentHint=*/ null, isActivityVisible(activity));
    }
  }

这里判断如果是后台线程那么还是走上面的 Application 类型的 get() 方法,否则调用 supportFragmentGet() 方法来获取 RequestManager。
看下 supportFragmentGet() 方法:

  /*RequestManagerRetriever*/
  private RequestManager supportFragmentGet(
      @NonNull Context context,
      @NonNull FragmentManager fm,
      @Nullable Fragment parentHint,
      boolean isParentVisible) {
    //(1)
    SupportRequestManagerFragment current =
        getSupportRequestManagerFragment(fm, parentHint, isParentVisible);
    RequestManager requestManager = current.getRequestManager();
    if (requestManager == null) {
      Glide glide = Glide.get(context);
      //(2)
      requestManager =
          factory.build(
              glide, current.getGlideLifecycle(), current.getRequestManagerTreeNode(), context);
      //(3)
      current.setRequestManager(requestManager);
    }
    return requestManager;
  }

  /*RequestManagerRetriever*/
  // 关注点(1)调用了 getSupportRequestManagerFragment() 方法
  private SupportRequestManagerFragment getSupportRequestManagerFragment(
      @NonNull final FragmentManager fm, @Nullable Fragment parentHint, boolean isParentVisible) {
    SupportRequestManagerFragment current =
        (SupportRequestManagerFragment) fm.findFragmentByTag(FRAGMENT_TAG);
    if (current == null) {
      current = pendingSupportRequestManagerFragments.get(fm);
      if (current == null) {
        //(4)
        current = new SupportRequestManagerFragment();
        current.setParentFragmentHint(parentHint);
        if (isParentVisible) {
          current.getGlideLifecycle().onStart();
        }
        pendingSupportRequestManagerFragments.put(fm, current);
        fm.beginTransaction().add(current, FRAGMENT_TAG).commitAllowingStateLoss();
        handler.obtainMessage(ID_REMOVE_SUPPORT_FRAGMENT_MANAGER, fm).sendToTarget();
      }
    }
    return current;
  }

  /*SupportRequestManagerFragment*/
  // 关注点(4)实例化了 SupportRequestManagerFragment
  public SupportRequestManagerFragment() {
    //(5)
    this(new ActivityFragmentLifecycle());
  }

在 supportFragmentGet() 方法中我标注了 3 个关注点,分别如下:

  • (1):获取了一个隐藏的 Fragment(在关注点(4)),在实例化 SupportRequestManagerFragment 的时候又实例化了
    ActivityFragmentLifecycle(在关注点(5)),ActivityFragmentLifecycle 实现了 Lifecycle,主要用来监听 Activity 与 Fragment 的生命周期。
  • (2):这里的 current.getGlideLifecycle() 就是关注点(1)中实例化的 ActivityFragmentLifecycle,这样 RequestManager 就与 ActivityFragmentLifecycle 进行了关联。
  • (3):将 RequestManager 设置到 SupportRequestManagerFragment 中。

所以经过(2)(3)实际是将 SupportRequestManagerFragment、RequestManager、ActivityFragmentLifecycle 都关联在一起了,又因为 Fragment 的生命周期和 Activity 是同步的,
所以 Activity 生命周期发生变化的时候,隐藏的 Fragment 的生命周期是同步变化的,这样 Glide 就可以根据这个 Fragment 的生命周期进行请求管理了。

是不是这样的呢?我们去看看 SupportRequestManagerFragment 的生命周期就知道了。

  /*SupportRequestManagerFragment*/
  @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();
  }

可以看到,ActivityFragmentLifecycle 确实与 SupportRequestManagerFragment 的生命周期关联起来了,我们这里只拿 onDestroy 来看看,
这里调用了 lifecycle#onDestroy(),间接调用了如下方法:

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

  /*LifecycleListener*/
  void onDestroy();

  /*RequestManager*/
  @Override
  public synchronized void onDestroy() {
    targetTracker.onDestroy();
    for (Target<?> target : targetTracker.getAll()) {
      clear(target);
    }
    targetTracker.clear();
    requestTracker.clearRequests();
    lifecycle.removeListener(this);
    lifecycle.removeListener(connectivityMonitor);
    mainHandler.removeCallbacks(addSelfToLifecycle);
    glide.unregisterRequestManager(this);
  }

可以看到,因为 RequestManager 是实现了 LifecycleListener 接口的,所以最终是调用了 RequestManager 的 onDestroy() 方法,
该方法里面主要做了取消所有进行中的请求并清除和回收所有已完成请求的资源。确实如我们所料,图片请求的生命周期就是由一个隐藏的 Fragment 的生命周期决定的。

这里总结下,RequestManagerRetriever#get() 方法如果传入 Application 类型的参数,那么图片请求的生命周期就是 Application 对象的生命周期,即应用程序的生命周期。
如果传入的是非 Application 类型的参数,那么会向当前的 Activity 当中添加一个隐藏的 Fragment,然后图片请求的生命周期由这个 Fragment 的生命周期决定。

2.1.3 小结

with() 方法主要做了如下事情:

  • 获取 AndroidManifest.xml 文件中配置的自定义模块与 @GlideModule 注解标识的自定义模块,然后进行 Glide 配置的更改与组件的替换。
  • 初始化构建 Glide 实例需要的各种配置信息,例如线程池、Bitmap 池、缓存策略、Engine 等,然后利用这些来创建具体的 Glide。
  • 将 Glide 的请求与 Application 或者隐藏的 Fragment 的生命周期进行绑定。

2.2 load()

load() 的重载方法有 9 个:

  • RequestManager#load(Bitmap bitmap);
  • RequestManager#load(Drawable drawable);
  • RequestManager#load(String string);
  • RequestManager#load(Uri uri);
  • RequestManager#load(File file);
  • RequestManager#load(Integer resourceId);
  • RequestManager#load(URL url);
  • RequestManager#load(byte[] model);
  • RequestManager#load(Object model);

点击进去发现这些重载方法最终都会调用 asDrawable().load(),所以这里只拿参数为字符串的来演示,也就是参数为图片链接。如下:

  /*RequestManager*/
  @Override
  public RequestBuilder<Drawable> load(@Nullable String string) {
    return asDrawable().load(string);
  }

2.2.1 RequestManager#asDrawable()

点击 asDrawable() 方法进去看看:

  /*RequestManager*/
  public RequestBuilder<Drawable> asDrawable() {
    return as(Drawable.class);
  }

  /*RequestManager*/
  public <ResourceType> RequestBuilder<ResourceType> as(
      @NonNull Class<ResourceType> resourceClass) {
    return new RequestBuilder<>(glide, this, resourceClass, context);
  }

  /*RequestBuilder*/
  protected RequestBuilder(
      @NonNull Glide glide,
      RequestManager requestManager,
      Class<TranscodeType> transcodeClass,
      Context context) {
    /*给 RequestBuilder 中的一些常量进行赋值*/
    this.glide = glide;
    this.requestManager = requestManager;
    this.transcodeClass = transcodeClass;
    this.context = context;
    this.transitionOptions = requestManager.getDefaultTransitionOptions(transcodeClass);
    this.glideContext = glide.getGlideContext();

    // 初始化请求监听
    initRequestListeners(requestManager.getDefaultRequestListeners());
    //(1)
    apply(requestManager.getDefaultRequestOptions());
  }

可以看到,经过一些列调用,该方法最终创建了 RequestBuilder 的实例并返回。其中关注点(1)是将默认选项应用于请求,点进去看看里面做了什么:

  /*RequestBuilder*/
  @Override
  public RequestBuilder<TranscodeType> apply(@NonNull BaseRequestOptions<?> requestOptions) {
    Preconditions.checkNotNull(requestOptions);
    return super.apply(requestOptions);
  }

这里又调用了父类的 apply() 方法:

  /*BaseRequestOptions*/
  public T apply(@NonNull BaseRequestOptions<?> o) {
    if (isAutoCloneEnabled) {
      return clone().apply(o);
    }
    BaseRequestOptions<?> other = o;

    if (isSet(other.fields, SIZE_MULTIPLIER)) {
      sizeMultiplier = other.sizeMultiplier;
    }
    if (isSet(other.fields, USE_UNLIMITED_SOURCE_GENERATORS_POOL)) {
      useUnlimitedSourceGeneratorsPool = other.useUnlimitedSourceGeneratorsPool;
    }
    if (isSet(other.fields, USE_ANIMATION_POOL)) {
      useAnimationPool = other.useAnimationPool;
    }
    if (isSet(other.fields, DISK_CACHE_STRATEGY)) {
      diskCacheStrategy = other.diskCacheStrategy;
    }
    if (isSet(other.fields, PRIORITY)) {
      priority = other.priority;
    }
    if (isSet(other.fields, ERROR_PLACEHOLDER)) {
      errorPlaceholder = other.errorPlaceholder;
      errorId = 0;
      fields &= ~ERROR_ID;
    }
    if (isSet(other.fields, ERROR_ID)) {
      errorId = other.errorId;
      errorPlaceholder = null;
      fields &= ~ERROR_PLACEHOLDER;
    }
    if (isSet(other.fields, PLACEHOLDER)) {
      placeholderDrawable = other.placeholderDrawable;
      placeholderId = 0;
      fields &= ~PLACEHOLDER_ID;
    }
    if (isSet(other.fields, PLACEHOLDER_ID)) {
      placeholderId = other.placeholderId;
      placeholderDrawable = null;
      fields &= ~PLACEHOLDER;
    }
    if (isSet(other.fields, IS_CACHEABLE)) {
      isCacheable = other.isCacheable;
    }
    if (isSet(other.fields, OVERRIDE)) {
      overrideWidth = other.overrideWidth;
      overrideHeight = other.overrideHeight;
    }
    if (isSet(other.fields, SIGNATURE)) {
      signature = other.signature;
    }
    if (isSet(other.fields, RESOURCE_CLASS)) {
      resourceClass = other.resourceClass;
    }
    if (isSet(other.fields, FALLBACK)) {
      fallbackDrawable = other.fallbackDrawable;
      fallbackId = 0;
      fields &= ~FALLBACK_ID;
    }
    if (isSet(other.fields, FALLBACK_ID)) {
      fallbackId = other.fallbackId;
      fallbackDrawable = null;
      fields &= ~FALLBACK;
    }
    if (isSet(other.fields, THEME)) {
      theme = other.theme;
    }
    if (isSet(other.fields, TRANSFORMATION_ALLOWED)) {
      isTransformationAllowed = other.isTransformationAllowed;
    }
    if (isSet(other.fields, TRANSFORMATION_REQUIRED)) {
      isTransformationRequired = other.isTransformationRequired;
    }
    if (isSet(other.fields, TRANSFORMATION)) {
      transformations.putAll(other.transformations);
      isScaleOnlyOrNoTransform = other.isScaleOnlyOrNoTransform;
    }
    if (isSet(other.fields, ONLY_RETRIEVE_FROM_CACHE)) {
      onlyRetrieveFromCache = other.onlyRetrieveFromCache;
    }

    // Applying options with dontTransform() is expected to clear our transformations.
    if (!isTransformationAllowed) {
      transformations.clear();
      fields &= ~TRANSFORMATION;
      isTransformationRequired = false;
      fields &= ~TRANSFORMATION_REQUIRED;
      isScaleOnlyOrNoTransform = true;
    }

    fields |= other.fields;
    options.putAll(other.options);

    return selfOrThrowIfLocked();
  }

可以看到,配置选项有很多,包括磁盘缓存策略,加载中的占位图,加载失败的占位图等。
到这里 asDrawable() 方法就看完了,接下来继续看 asDrawable().load(string) 中的 load() 方法。

2.2.2 RequestBuilder#load()

点击 load() 方法进去看看:

  /*RequestBuilder*/
  @Override
  public RequestBuilder<TranscodeType> load(@Nullable String string) {
    return loadGeneric(string);
  }

  /*RequestBuilder*/
  private RequestBuilder<TranscodeType> loadGeneric(@Nullable Object model) {
    this.model = model;
    isModelSet = true;
    return this;
  }

发现这个方法非常简单,首先调用了 loadGeneric() 方法,然后 loadGeneric() 方法中将传进来的图片资源赋值给了变量 model,最后用 isModelSet 标记已经调用过 load() 方法了。

2.2.3 小结

load() 方法就比较简单了,主要是通过前面实例化的 Glide 与 RequestManager 来创建 RequestBuilder,然后将传进来的参数赋值给 model。接下来主要看看 into() 方法。

2.3 into()

我们发现,前两个方法都没有涉及到图片的请求、缓存、解码等逻辑,其实都在 into() 方法中,所以这个方法也是最复杂的。

点击 into() 方法进去看看:

  /*RequestBuilder*/
  public ViewTarget<ImageView, TranscodeType> into(@NonNull ImageView view) {
    Util.assertMainThread();
    Preconditions.checkNotNull(view);

    BaseRequestOptions<?> requestOptions = this;
    if (!requestOptions.isTransformationSet()
        && requestOptions.isTransformationAllowed()
        && view.getScaleType() != null) {
      /*将 ImageView 的 scaleType 设置给 BaseRequestOptions(ImageView 的默认 scaleType 为 fitCenter)*/
      switch (view.getScaleType()) {
        case CENTER_CROP:
          requestOptions = requestOptions.clone().optionalCenterCrop();
          break;
        case CENTER_INSIDE:
          requestOptions = requestOptions.clone().optionalCenterInside();
          break;
        case FIT_CENTER:
        case FIT_START:
        case FIT_END:
          requestOptions = requestOptions.clone().optionalFitCenter();
          break;
        case FIT_XY:
          requestOptions = requestOptions.clone().optionalCenterInside();
          break;
        case CENTER:
        case MATRIX:
        default:
          // Do nothing.
      }
    }
    //(1)buildImageViewTarget()
    return into(
        glideContext.buildImageViewTarget(view, transcodeClass),
        /*targetListener=*/ null,
        requestOptions,
        Executors.mainThreadExecutor());
  }
  
  /*RequestBuilder*/
  private <Y extends Target<TranscodeType>> Y into(
      @NonNull Y target,
      @Nullable RequestListener<TranscodeType> targetListener,
      BaseRequestOptions<?> options,
      Executor callbackExecutor) {
    Preconditions.checkNotNull(target);
    if (!isModelSet) {
      throw new IllegalArgumentException("You must call #load() before calling #into()");
    }

    //(2)
    Request request = buildRequest(target, targetListener, options, callbackExecutor);

    Request previous = target.getRequest();
    if (request.isEquivalentTo(previous)
        && !isSkipMemoryCacheWithCompletePreviousRequest(options, previous)) {
      if (!Preconditions.checkNotNull(previous).isRunning()) {
        previous.begin();
      }
      return target;
    }

    requestManager.clear(target);
    target.setRequest(request);
    //(3)
    requestManager.track(target, request);

    return target;
  }

可以看到,里面又调用了 into() 的另一个重载方法。这里我标记了 3 个关注点,分别是获取 ImageViewTarget、构建请求和执行请求,后面我们就主要分析这 3 个关注点。

2.3.1 GlideContext#buildImageViewTarget()

点击 RequestBuilder#into() 中的关注点(1)进去看看:

  /*GlideContext*/
  public <X> ViewTarget<ImageView, X> buildImageViewTarget(
      @NonNull ImageView imageView, @NonNull Class<X> transcodeClass) {
    return imageViewTargetFactory.buildTarget(imageView, transcodeClass);
  }

  /*ImageViewTargetFactory*/
  public <Z> ViewTarget<ImageView, Z> buildTarget(
      @NonNull ImageView view, @NonNull Class<Z> clazz) {
    if (Bitmap.class.equals(clazz)) {
      return (ViewTarget<ImageView, Z>) new BitmapImageViewTarget(view);
    } else if (Drawable.class.isAssignableFrom(clazz)) {
      return (ViewTarget<ImageView, Z>) new DrawableImageViewTarget(view);
    } else {
      throw new IllegalArgumentException(
          "Unhandled class: " + clazz + ", try .as*(Class).transcode(ResourceTranscoder)");
    }
  }

可以看到,这里是通过 ImageViewTargetFactory#buildTarget(imageView, transcodeClass) 来获取的,其中 ImageViewTargetFactory 是在 Glide 的构造函数中实例化的,而 transcodeClass 是 load() 方法中 asDrawable()--as(Drawable.class) 传进来的。然后 buildTarget() 方法中就是根据这个 transcodeClass 来返回对应的 ViewTarget,所以默认情况下都是返回 DrawableImageViewTarget,只有专门指定 asBitmap() 才会返回 BitmapImageViewTarget,如下指定:

 Glide.with(this).asBitmap().load(url).into(imageView);

接下来继续看关注点(2)。

2.3.2 RequestBuilder#buildRequest()

点击 RequestBuilder#into() 中的关注点(2)进去看看:

  /*RequestBuilder*/
  private Request buildRequest(...) {
    return buildRequestRecursive(
        /*requestLock=*/ new Object(),
        target,
        targetListener,
        /*parentCoordinator=*/ null,
        transitionOptions,
        requestOptions.getPriority(),
        requestOptions.getOverrideWidth(),
        requestOptions.getOverrideHeight(),
        requestOptions,
        callbackExecutor);
  }

这里又调用了 buildRequestRecursive() 方法:

  /*RequestBuilder*/
  private Request buildRequestRecursive(...) {

    // Build the ErrorRequestCoordinator first if necessary so we can update parentCoordinator.
    ErrorRequestCoordinator errorRequestCoordinator = null;
    //(1)
    if (errorBuilder != null) {
      errorRequestCoordinator = new ErrorRequestCoordinator(requestLock, parentCoordinator);
      parentCoordinator = errorRequestCoordinator;
    }

    //(2)递归构建缩略图请求
    Request mainRequest =
        buildThumbnailRequestRecursive(...);

    if (errorRequestCoordinator == null) {
      return mainRequest;
    }
    ...

    //(3)递归构建错误请求
    Request errorRequest =
        errorBuilder.buildRequestRecursive(...);
    errorRequestCoordinator.setRequests(mainRequest, errorRequest);
    return errorRequestCoordinator;
  }

可以看到,只有关注点(1)中的 errorBuilder 不为空,即我们设置了在主请求失败时开始新的请求(如下设置) 才会走到关注点(3)去递归构建错误请求。

// 设置在主请求失败时开始新的请求
Glide.with(this).load(url).error(Glide.with(this).load(fallbackUrl)).into(imageView);

因为我什么都没有设置,所以这里看关注点(2)的递归构建缩略图请求即可。

点击 buildThumbnailRequestRecursive() 方法进去看看:

  /*RequestBuilder*/
  private Request buildThumbnailRequestRecursive(
      Object requestLock,
      Target<TranscodeType> target,
      RequestListener<TranscodeType> targetListener,
      @Nullable RequestCoordinator parentCoordinator,
      TransitionOptions<?, ? super TranscodeType> transitionOptions,
      Priority priority,
      int overrideWidth,
      int overrideHeight,
      BaseRequestOptions<?> requestOptions,
      Executor callbackExecutor) {
    if (thumbnailBuilder != null) { //(1)
      
      ...

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

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

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

可以看到,这里我标记了 3 个大的关注点,分别如下:

  • (1):设置了缩略图请求的时候会走这里,如下设置:
// 设置缩略图请求
Glide.with(this).load(url).thumbnail(Glide.with(this).load(thumbnailUrl)).into(imageView);

其中关注点(1.2)是获取一个原图请求,关注点(1.3)是根据设置的 thumbnailBuilder 来生成缩略图请求,然后关注点(1.1)是创建一个协调器,用来协调这两个请求,这样可以同时进行原图与缩略图的请求。

  • (2):设置了缩略图的缩略比例的时候会走这里,如下设置:
// 设置缩略图的缩略比例
Glide.with(this).load(url).thumbnail(0.5f).into(imageView);

与关注点(1)一样,也是通过一个协调器来同时进行原图与缩略图的请求,不同的是这里生成缩略图用的是缩略比例。

  • (3):没有缩略图相关设置,直接获取原图请求。

因为我什么都没有设置,所以这里看关注点(3)即可。点击 obtainRequest() 方法进去看看:

  /*RequestBuilder*/
  private Request obtainRequest(...) {
    return SingleRequest.obtain(...);
  }

  /*SingleRequest*/
  public static <R> SingleRequest<R> obtain(...) {
    return new SingleRequest<>(...);
  }

  /*SingleRequest*/
  private SingleRequest(
      Context context,
      GlideContext glideContext,
      @NonNull Object requestLock,
      @Nullable Object model,
      Class<R> transcodeClass,
      BaseRequestOptions<?> requestOptions,
      int overrideWidth,
      int overrideHeight,
      Priority priority,
      Target<R> target,
      @Nullable RequestListener<R> targetListener,
      @Nullable List<RequestListener<R>> requestListeners,
      RequestCoordinator requestCoordinator,
      Engine engine,
      TransitionFactory<? super R> animationFactory,
      Executor callbackExecutor) {
    this.requestLock = requestLock;
    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.requestListeners = requestListeners;
    this.requestCoordinator = requestCoordinator;
    this.engine = engine;
    this.animationFactory = animationFactory;
    this.callbackExecutor = callbackExecutor;
    status = Status.PENDING;

    if (requestOrigin == null && glideContext.isLoggingRequestOriginsEnabled()) {
      requestOrigin = new RuntimeException("Glide request origin trace");
    }
  }

可以看到,最终是实例化了一个 SingleRequest 的实例,也就是说构建请求这一步已经完成了,接下来分析执行请求这一步。

2.3.3 RequestManager#track()

点击 RequestBuilder#into() 中的关注点(3)进去看看:

  /*RequestManager*/
  synchronized void track(@NonNull Target<?> target, @NonNull Request request) {
    targetTracker.track(target);
    requestTracker.runRequest(request);
  }

点击 track() 进去:

public final class TargetTracker implements LifecycleListener {
  private final Set<Target<?>> targets =
      Collections.newSetFromMap(new WeakHashMap<Target<?>, Boolean>());

  public void track(@NonNull Target<?> target) {
    targets.add(target);
  }
}

可以看到,targetTracker.track(target) 是将一个 target 加入 Set 集合中,继续看下 runRequest() 方法:

  /*RequestTracker*/
  private final Set<Request> requests =
      Collections.newSetFromMap(new WeakHashMap<Request, Boolean>());
  private final List<Request> pendingRequests = new ArrayList<>();

  public void runRequest(@NonNull Request request) {
    requests.add(request);
    if (!isPaused) {
      request.begin();
    } else {
      request.clear();
      if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "Paused, delaying request");
      }
      pendingRequests.add(request);
    }
  }

可以看到,首先将请求加入一个 Set 集合,然后判断是否暂停状态,是则清空请求,并将该请求加入待处理的请求集合中;不是暂停状态则开始请求。

点击 begin() 方法进去看看:

  /*SingleRequest*/
  @Override
  public void begin() {
    synchronized (requestLock) {
      assertNotCallingCallbacks();
      stateVerifier.throwIfRecycled();
      startTime = LogTime.getLogTime();
      /*如果加载的资源为空,则调用加载失败的回调*/
      if (model == null) {
        if (Util.isValidDimensions(overrideWidth, overrideHeight)) {
          width = overrideWidth;
          height = overrideHeight;
        }

        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 (status == Status.COMPLETE) {
        // 资源加载完成
        onResourceReady(resource, DataSource.MEMORY_CACHE);
        return;
      }

      status = Status.WAITING_FOR_SIZE;
      //(1)
      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));
      }
    }
  }

如上,关键代码在关注点(1),这里做了一个判断,如果我们设置了 overrideWidth 和 overrideHeight(如下设置),则直接调用 onSizeReady() 方法,否则调用 getSize() 方法(第一次加载才会调用)。

// 设置加载图片的宽高为 100x100 px
Glide.with(this).load(url).override(100,100).into(imageView);

getSize() 方法的作用是通过 ViewTreeObserver 来监听 ImageView 的宽高,拿到宽高后最终也是调用 onSizeReady() 方法。

接下来看下 onSizeReady() 方法:

  /*SingleRequest*/
  @Override
  public void onSizeReady(int width, int height) {
    stateVerifier.throwIfRecycled();
    synchronized (requestLock) {

      ...

      /*根据缩略比例获取图片宽高*/
      float sizeMultiplier = requestOptions.getSizeMultiplier();
      this.width = maybeApplySizeMultiplier(width, sizeMultiplier);
      this.height = maybeApplySizeMultiplier(height, sizeMultiplier);

      // 开始加载
      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,
              callbackExecutor);
      
      ...

    }
  }

可以看到,这里开始加载了,继续跟进:

  /*Engine*/
  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,
      Executor callbackExecutor) {
    long startTime = VERBOSE_IS_LOGGABLE ? LogTime.getLogTime() : 0;

    // 构建缓存 key
    EngineKey key =
        keyFactory.buildKey(
            model,
            signature,
            width,
            height,
            transformations,
            resourceClass,
            transcodeClass,
            options);

    EngineResource<?> memoryResource;
    synchronized (this) {
      // 从内存中加载资源
      memoryResource = loadFromMemory(key, isMemoryCacheable, startTime);

      // 内存中没有,则等待当前正在执行的或开始一个新的 EngineJob
      if (memoryResource == null) {
        return waitForExistingOrStartNewJob(
            glideContext,
            model,
            signature,
            width,
            height,
            resourceClass,
            transcodeClass,
            priority,
            diskCacheStrategy,
            transformations,
            isTransformationRequired,
            isScaleOnlyOrNoTransform,
            options,
            isMemoryCacheable,
            useUnlimitedSourceExecutorPool,
            useAnimationPool,
            onlyRetrieveFromCache,
            cb,
            callbackExecutor,
            key,
            startTime);
      }
    }

    // 加载完成回调
    cb.onResourceReady(memoryResource, DataSource.MEMORY_CACHE);
    return null;
  }

可以看到,这里首先构建缓存 key,然后利用这个 key 获取缓存中的资源,如果内存中没有,则等待当前正在执行的或开始一个新的 EngineJob,内存中有则调用加载完成的回调。这里我们先不讨论缓存相关的,下一篇文章再讲。所以默认是第一次加载,点击 waitForExistingOrStartNewJob() 方法进去看看:

  /*Engine*/
  private <R> LoadStatus waitForExistingOrStartNewJob(
      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,
      Executor callbackExecutor,
      EngineKey key,
      long startTime) {

    //(1)
    EngineJob<?> current = jobs.get(key, onlyRetrieveFromCache);
    if (current != null) {
      current.addCallback(cb, callbackExecutor);
      if (VERBOSE_IS_LOGGABLE) {
        logWithTimeAndKey("Added to existing load", startTime, key);
      }
      return new LoadStatus(cb, current);
    }

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

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

    // 将 EngineJob 放到一个 map 集合中
    jobs.put(key, engineJob);
    // 添加回调
    engineJob.addCallback(cb, callbackExecutor);
    //(4)
    engineJob.start(decodeJob);

    if (VERBOSE_IS_LOGGABLE) {
      logWithTimeAndKey("Started new load", startTime, key);
    }
    // 返回加载状态
    return new LoadStatus(cb, engineJob);
  }

这里标记了 4 个关注点,分别如下:

  • (1):从 map 集合中获取 EngineJob,如果不为空表示当前有正在执行的 EngineJob,添加回调并返回加载状态。
  • (2):使用 EngineJob 工厂构建了一个 EngineJob,该类主要用来管理加载以及当加载完成时通知回调。
  • (3):使用 DecodeJob 工厂构建了一个 DecodeJob,该类主要负责图片的解码,实现了 Runnable 接口,属于一个任务。
  • (4):这里调用了 EngineJob#start(),点击进去看看:
  /*EngineJob*/
  public synchronized void start(DecodeJob<R> decodeJob) {
    this.decodeJob = decodeJob;
    GlideExecutor executor =
        decodeJob.willDecodeFromCache() ? diskCacheExecutor : getActiveSourceExecutor();
    executor.execute(decodeJob);
  }

这里直接将 DecodeJob 任务放到了一个线程池中去执行,也就是说从这里开始切换到子线程了,那么我们看下 DecodeJob 的 run() 方法做了什么:

  /*DecodeJob*/
  @Override
  public void run() {
    GlideTrace.beginSectionFormat("DecodeJob#run(model=%s)", model);
    DataFetcher<?> localFetcher = currentFetcher;
    try {
      // 被取消,则调用加载失败的回调
      if (isCancelled) {
        notifyFailed();
        return;
      }
      // 执行
      runWrapped();
    } catch (CallbackException e) {
      throw e;
    } catch (Throwable t) {

    ...

    } finally {
      // Keeping track of the fetcher here and calling cleanup is excessively paranoid, we call
      // close in all cases anyway.
      if (localFetcher != null) {
        localFetcher.cleanup();
      }
      GlideTrace.endSection();
    }
  }

继续 runWrapped() 方法:

  /*DecodeJob*/
  private void runWrapped() {
    switch (runReason) {
      case INITIALIZE:
        /*(4.1)*/
        // 获取资源状态
        stage = getNextStage(Stage.INITIALIZE);
        // 根据资源状态获取资源执行器
        currentGenerator = getNextGenerator();
        //(4.2)执行
        runGenerators();
        break;
      case SWITCH_TO_SOURCE_SERVICE:
        runGenerators();
        break;
      case DECODE_DATA:
        decodeFromRetrievedData();
        break;
      default:
        throw new IllegalStateException("Unrecognized run reason: " + runReason);
    }
  }

  /*DecodeJob*/
  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);
    }
  }

  /*DecodeJob*/
  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);
    }
  }

runReason 的默认值为 INITIALIZE,所以走的是第一个 case。由于我们配置了禁用内存与磁盘缓存,所以关注点(4.1)中得到的 stage 为 SOURCE,currentGenerator 为 SourceGenerator。拿到资源执行器接着就是执行了,点击关注点(4.2)的 runGenerators() 方法进去看看:

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

      if (stage == Stage.SOURCE) {
        reschedule();
        return;
      }
    }
  }

因为 currentGenerator 在这里为 SourceGenerator,所以调用 startNext() 方法的时候实际调用的是 SourceGenerator#startNext()。该方法执行完返回的结果为 true,所以 while 循环是进不去的。

那么我们接下来看下 SourceGenerator#startNext():

  /*SourceGenerator*/
  @Override
  public boolean startNext() {

    ...

    loadData = null;
    boolean started = false;
    while (!started && hasNextModelLoader()) {
      //(1)
      loadData = helper.getLoadData().get(loadDataListIndex++);
      if (loadData != null
          && (helper.getDiskCacheStrategy().isDataCacheable(loadData.fetcher.getDataSource())
              || helper.hasLoadPath(loadData.fetcher.getDataClass()))) {
        started = true;
        //(2)
        startNextLoad(loadData);
      }
    }
    return started;
  }

这里我标记了 2 个关注,分别如下:

  • SourceGenerator#startNext() 中的关注点(1)
    通过 helper#getLoadData() 获取 LoadData 集合,实际集合里面也就只有一个元素,然后通过索引获取一个 LoadData,看看里面是怎么获取 LoadData 集合的:
  /*DecodeHelper*/
  List<LoadData<?>> getLoadData() {
    if (!isLoadDataSet) {
      isLoadDataSet = true;
      loadData.clear();
      List<ModelLoader<Object, ?>> modelLoaders = glideContext.getRegistry().getModelLoaders(model);
      //noinspection ForLoopReplaceableByForEach to improve perf
      for (int i = 0, size = modelLoaders.size(); i < size; i++) {
        ModelLoader<Object, ?> modelLoader = modelLoaders.get(i);
        // 关注点
        LoadData<?> current = modelLoader.buildLoadData(model, width, height, options);
        if (current != null) {
          loadData.add(current);
        }
      }
    }
    return loadData;
  }

可以看到,这里是通过 ModelLoader 对象的 buildLoadData() 方法获取的 LoadData。由于是从网络加载数据,所以这里实际调用的是 HttpGlideUrlLoader#buildLoadData(),点进去看看:

  /*HttpGlideUrlLoader*/
  @Override
  public LoadData<InputStream> buildLoadData(
      @NonNull GlideUrl model, int width, int height, @NonNull Options options) {
    // GlideUrls memoize parsed URLs so caching them saves a few object instantiations and time
    // spent parsing urls.
    GlideUrl url = model;
    if (modelCache != null) {
      url = modelCache.get(model, 0, 0);
      if (url == null) {
        modelCache.put(model, 0, 0, model);
        url = model;
      }
    }
    int timeout = options.get(TIMEOUT);
    // 关注点
    return new LoadData<>(url, new HttpUrlFetcher(url, timeout));
  }

缓存相关的不看,看到最后一行实例化 LoadData 的时候顺带实例化了 HttpUrlFetcher,这个后面会用到。

  • SourceGenerator#startNext() 中的关注点(2)
    这里表示开始加载了,点进去看看:
  /*SourceGenerator*/
  private void startNextLoad(final LoadData<?> toStart) {
    loadData.fetcher.loadData(
        helper.getPriority(),
        new DataCallback<Object>() {
          @Override
          public void onDataReady(@Nullable Object data) {
            if (isCurrentRequest(toStart)) {
              onDataReadyInternal(toStart, data);
            }
          }

          @Override
          public void onLoadFailed(@NonNull Exception e) {
            if (isCurrentRequest(toStart)) {
              onLoadFailedInternal(toStart, e);
            }
          }
        });
  }

这里的 loadData.fetcher 就是刚刚实例化 LoadData 的时候传进来的 HttpUrlFetcher,所以这里调用的是 HttpUrlFetcher#loadData():

  /*HttpUrlFetcher*/
  @Override
  public void loadData(
      @NonNull Priority priority, @NonNull DataCallback<? super InputStream> callback) {
    long startTime = LogTime.getLogTime();
    try {
      //(1)通过重定向加载数据
      InputStream result = loadDataWithRedirects(glideUrl.toURL(), 0, null, glideUrl.getHeaders());
      //(2)加载成功,回调数据
      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));
      }
    }
  }

这里标记了 2 个关注点,分别如下:

  • HttpUrlFetcher#loadData() 中的关注点(1)
    这里加载完数据后返回了 InputStream,看看内部是怎么实现的:
  /*HttpUrlFetcher*/
  private InputStream loadDataWithRedirects(
      URL url, int redirects, URL lastUrl, Map<String, String> headers) throws IOException {
    
    ...

    // 获取 HttpURLConnection 实例
    urlConnection = connectionFactory.build(url);
    for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
      urlConnection.addRequestProperty(headerEntry.getKey(), headerEntry.getValue());
    }
    urlConnection.setConnectTimeout(timeout);
    urlConnection.setReadTimeout(timeout);
    urlConnection.setUseCaches(false);
    urlConnection.setDoInput(true);

    // Stop the urlConnection instance of HttpUrlConnection from following redirects so that
    // redirects will be handled by recursive calls to this method, loadDataWithRedirects.
    urlConnection.setInstanceFollowRedirects(false);

    // Connect explicitly to avoid errors in decoders if connection fails.
    urlConnection.connect();
    // Set the stream so that it's closed in cleanup to avoid resource leaks. See #2352.
    stream = urlConnection.getInputStream();
    if (isCancelled) {
      return null;
    }
    final int statusCode = urlConnection.getResponseCode();
    if (isHttpOk(statusCode)) { // 请求成功
      // 获取 InputStream
      return getStreamForSuccessfulRequest(urlConnection);
    } else if (isHttpRedirect(statusCode)) { // 重定向请求
      String redirectUrlString = urlConnection.getHeaderField("Location");
      if (TextUtils.isEmpty(redirectUrlString)) {
        throw new HttpException("Received empty or null redirect url");
      }
      URL redirectUrl = new URL(url, redirectUrlString);
      // Closing the stream specifically is required to avoid leaking ResponseBodys in addition
      // to disconnecting the url connection below. See #2352.
      cleanup();
      return loadDataWithRedirects(redirectUrl, redirects + 1, url, headers);
    } else if (statusCode == INVALID_STATUS_CODE) {
      throw new HttpException(statusCode);
    } else {
      throw new HttpException(urlConnection.getResponseMessage(), statusCode);
    }
  }

  /*HttpUrlFetcher*/
  private InputStream getStreamForSuccessfulRequest(HttpURLConnection urlConnection)
      throws IOException {
    if (TextUtils.isEmpty(urlConnection.getContentEncoding())) {
      int contentLength = urlConnection.getContentLength();
      stream = ContentLengthInputStream.obtain(urlConnection.getInputStream(), contentLength);
    } else {
      if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Got non empty content encoding: " + urlConnection.getContentEncoding());
      }
      stream = urlConnection.getInputStream();
    }
    return stream;
  }

可以看到,原来 Glide 底层是采用 HttpURLConnection 来进行网络请求的,请求成功后返回了 InputStream。

  • HttpUrlFetcher#loadData() 中的关注点(2)
    现在 InputStream 已经拿到了,回去关注点(2)中看下是怎么将 InputStream 回调出去的。
    关注点(2)调用 callback.onDataReady(result) 会走如下一系列调用:
    /*MultiModelLoader*/
    @Override
    public void onDataReady(@Nullable Data data) {
      if (data != null) {
        // 执行这里
        callback.onDataReady(data);
      } else {
        startNextOrFail();
      }
    }
  
  /*SourceGenerator*/
  private void startNextLoad(final LoadData<?> toStart) {
    loadData.fetcher.loadData(
        helper.getPriority(),
        new DataCallback<Object>() {
          @Override
          public void onDataReady(@Nullable Object data) {
            if (isCurrentRequest(toStart)) {
              // 执行这里
              onDataReadyInternal(toStart, data);
            }
          }

          @Override
          public void onLoadFailed(@NonNull Exception e) {
            if (isCurrentRequest(toStart)) {
              onLoadFailedInternal(toStart, e);
            }
          }
        });
  }

  /*SourceGenerator*/
  void onDataReadyInternal(LoadData<?> loadData, 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*/
  @Override
  public void onDataFetcherReady(
      Key sourceKey, Object data, DataFetcher<?> fetcher, DataSource dataSource, Key attemptedKey) {
    this.currentSourceKey = sourceKey;
    this.currentData = data;
    this.currentFetcher = fetcher;
    this.currentDataSource = dataSource;
    this.currentAttemptingKey = attemptedKey;
    if (Thread.currentThread() != currentThread) {
      runReason = RunReason.DECODE_DATA;
      callback.reschedule(this);
    } else {
      GlideTrace.beginSection("DecodeJob.decodeFromRetrievedData");
      try {
        // (1)解码
        decodeFromRetrievedData();
      } finally {
        GlideTrace.endSection();
      }
    }
  }

可以看到,经过一系列调用,最终走到关注点(1),这里就开始解码数据了,点进去看看:

  /*DecodeJob*/
  private void decodeFromRetrievedData() {
    Resource<R> resource = null;
    try {
      //(1)解码
      resource = decodeFromData(currentFetcher, currentData, currentDataSource);
    } catch (GlideException e) {
      e.setLoggingDetails(currentAttemptingKey, currentDataSource);
      throwables.add(e);
    }
    if (resource != null) {
      //(2)解码完成,通知下去
      notifyEncodeAndRelease(resource, currentDataSource);
    } else {
      runGenerators();
    }
  }

这里标记了 2 个关注点,分别如下:

  • DecodeJob#decodeFromRetrievedData() 中的关注点(1)
    点击关注点(1)进去看看:
  /*DecodeJob*/
  private <Data> Resource<R> decodeFromData(
      DataFetcher<?> fetcher, Data data, DataSource dataSource) throws GlideException {
    try {
      if (data == null) {
        return null;
      }
      long startTime = LogTime.getLogTime();
      Resource<R> result = decodeFromFetcher(data, dataSource);
      if (Log.isLoggable(TAG, Log.VERBOSE)) {
        logWithTimeAndKey("Decoded result " + result, startTime);
      }
      return result;
    } finally {
      fetcher.cleanup();
    }
  }

  /*DecodeJob*/
  private <Data> Resource<R> decodeFromFetcher(Data data, DataSource dataSource)
      throws GlideException {
    // 获取解码器,解码器里面封装了 DecodePath,它就是用来解码转码的
    LoadPath<Data, ?, R> path = decodeHelper.getLoadPath((Class<Data>) data.getClass());
    // 通过解码器解析数据
    return runLoadPath(data, dataSource, path);
  }

  /*DecodeJob*/
  private <Data, ResourceType> Resource<R> runLoadPath(
      Data data, DataSource dataSource, LoadPath<Data, ResourceType, R> path)
      throws GlideException {
    Options options = getOptionsWithHardwareConfig(dataSource);
    DataRewinder<Data> rewinder = glideContext.getRegistry().getRewinder(data);
    try {
      // ResourceType in DecodeCallback below is required for compilation to work with gradle.
      // 将解码任务传递给 LoadPath 完成
      return path.load(
          rewinder, options, width, height, new DecodeCallback<ResourceType>(dataSource));
    } finally {
      rewinder.cleanup();
    }
  }

  /*LoadPath*/
  public Resource<Transcode> load(
      DataRewinder<Data> rewinder,
      @NonNull Options options,
      int width,
      int height,
      DecodePath.DecodeCallback<ResourceType> decodeCallback)
      throws GlideException {
    List<Throwable> throwables = Preconditions.checkNotNull(listPool.acquire());
    try {
      return loadWithExceptionList(rewinder, options, width, height, decodeCallback, throwables);
    } finally {
      listPool.release(throwables);
    }
  }

  /*LoadPath*/
  private Resource<Transcode> loadWithExceptionList(
      DataRewinder<Data> rewinder,
      @NonNull Options options,
      int width,
      int height,
      DecodePath.DecodeCallback<ResourceType> decodeCallback,
      List<Throwable> exceptions)
      throws GlideException {
    Resource<Transcode> result = null;
    //noinspection ForLoopReplaceableByForEach to improve perf
    for (int i = 0, size = decodePaths.size(); i < size; i++) {
      DecodePath<Data, ResourceType, Transcode> path = decodePaths.get(i);
      try {
        // 开始解析数据
        result = path.decode(rewinder, width, height, options, decodeCallback);
      } catch (GlideException e) {
        exceptions.add(e);
      }
      if (result != null) {
        break;
      }
    }

    if (result == null) {
      throw new GlideException(failureMessage, new ArrayList<>(exceptions));
    }

    return result;
  }

可以看到,上面主要是获取解码器(LoadPath),然后解码器里面是封装了 DecodePath,经过一系列调用,最后其实是交给 DecodePath 的 decode() 方法来真正开始解析数据的。

点击 decode() 方法进去看看:

  /*DecodePath*/
  public Resource<Transcode> decode(
      DataRewinder<DataType> rewinder,
      int width,
      int height,
      @NonNull Options options,
      DecodeCallback<ResourceType> callback)
      throws GlideException {
    //(1)
    Resource<ResourceType> decoded = decodeResource(rewinder, width, height, options);
    //(2)
    Resource<ResourceType> transformed = callback.onResourceDecoded(decoded);
    //(3)
    return transcoder.transcode(transformed, options);
  }

这里我标记了 3 个关注点,分别如下:

  • DecodePath#decode() 中的关注点(1)
    这里是一个解码过程,主要是将原始数据解码成原始图片。点进去看看:
  /*DecodePath*/
  private Resource<ResourceType> decodeResource(
      DataRewinder<DataType> rewinder, int width, int height, @NonNull Options options)
      throws GlideException {
    List<Throwable> exceptions = Preconditions.checkNotNull(listPool.acquire());
    try {
      return decodeResourceWithList(rewinder, width, height, options, exceptions);
    } finally {
      listPool.release(exceptions);
    }
  }

  /*DecodePath*/
  private Resource<ResourceType> decodeResourceWithList(
      DataRewinder<DataType> rewinder,
      int width,
      int height,
      @NonNull Options options,
      List<Throwable> exceptions)
      throws GlideException {
    Resource<ResourceType> result = null;
    //noinspection ForLoopReplaceableByForEach to improve perf
    for (int i = 0, size = decoders.size(); i < size; i++) {
      ResourceDecoder<DataType, ResourceType> decoder = decoders.get(i);
      try {
        DataType data = rewinder.rewindAndGet();
        if (decoder.handles(data, options)) {
          data = rewinder.rewindAndGet();
          // 关注点
          result = decoder.decode(data, width, height, options);
        }
        // Some decoders throw unexpectedly. If they do, we shouldn't fail the entire load path, but
        // instead log and continue. See #2406 for an example.
      } catch (IOException | RuntimeException | OutOfMemoryError e) {

      ...

    }

    ...

    return result;
  }

可以看到,这里遍历拿到可以解码当前数据的资源解码器,然后调用 decode() 方法进行解码。因为当前数据是 InputStream,所以这里遍历拿到的 ResourceDecoder 其实是 StreamBitmapDecoder,所以调用的是 StreamBitmapDecoder#decode()。

继续看 StreamBitmapDecoder#decode():

  /*StreamBitmapDecoder*/
  @Override
  public Resource<Bitmap> decode(
      @NonNull InputStream source, int width, int height, @NonNull Options options)
      throws IOException {

    // Use to fix the mark limit to avoid allocating buffers that fit entire images.
    final RecyclableBufferedInputStream bufferedStream;
    final boolean ownsBufferedStream;
    if (source instanceof RecyclableBufferedInputStream) {
      bufferedStream = (RecyclableBufferedInputStream) source;
      ownsBufferedStream = false;
    } else {
      bufferedStream = new RecyclableBufferedInputStream(source, byteArrayPool);
      ownsBufferedStream = true;
    }

    // Use to retrieve exceptions thrown while reading.
    // TODO(#126): when the framework no longer returns partially decoded Bitmaps or provides a
    // way to determine if a Bitmap is partially decoded, consider removing.
    ExceptionCatchingInputStream exceptionStream =
        ExceptionCatchingInputStream.obtain(bufferedStream);

    // Use to read data.
    // Ensures that we can always reset after reading an image header so that we can still
    // attempt to decode the full image even when the header decode fails and/or overflows our read
    // buffer. See #283.
    MarkEnforcingInputStream invalidatingStream = new MarkEnforcingInputStream(exceptionStream);
    UntrustedCallbacks callbacks = new UntrustedCallbacks(bufferedStream, exceptionStream);
    try {
      // (1)
      return downsampler.decode(invalidatingStream, width, height, options, callbacks);
    } finally {
      exceptionStream.release();
      if (ownsBufferedStream) {
        bufferedStream.release();
      }
    }
  }

  /*Downsampler*/
  public Resource<Bitmap> decode(...)
      throws IOException {
    return decode(...);
  }

  /*Downsampler*/
  private Resource<Bitmap> decode(...)
      throws IOException {

    ...

    try {
      // (2)根据输入流解码得到 Bitmap
      Bitmap result =
          decodeFromWrappedStreams(
              imageReader,
              bitmapFactoryOptions,
              downsampleStrategy,
              decodeFormat,
              preferredColorSpace,
              isHardwareConfigAllowed,
              requestedWidth,
              requestedHeight,
              fixBitmapToRequestedDimensions,
              callbacks);
      // (3)将 Bitmap 包装成 Resource<Bitmap> 返回
      return BitmapResource.obtain(result, bitmapPool);
    } finally {
      releaseOptions(bitmapFactoryOptions);
      byteArrayPool.put(bytesForOptions);
    }
  }

可以看到,关注点(1)中调用了 Downsampler#decode(),然后走到关注点(2)将输入流解码得到 Bitmap,最后将 Bitmap 包装成 Resource<Bitmap> 返回。关注点(2)中其实就是使用 BitmapFactory 根据 exif 方向对图像进行下采样,解码和旋转,最后调用原生的 BitmapFactory#decodeStream() 得到的 Bitmap,里面的细节就不展开了。

  • DecodePath#decode() 中的关注点(2)
    这里会调用 callback#onResourceDecoded() 进行回调,这里是回调到 DecodeJob#onResourceDecoded():
    /*DecodeJob*/
    @Override
    public Resource<Z> onResourceDecoded(@NonNull Resource<Z> decoded) {
      return DecodeJob.this.onResourceDecoded(dataSource, decoded);
    }

继续跟进:

  /*DecodeJob*/
  <Z> Resource<Z> onResourceDecoded(DataSource dataSource, @NonNull Resource<Z> decoded) {
    @SuppressWarnings("unchecked")
    Class<Z> resourceSubClass = (Class<Z>) decoded.get().getClass();
    Transformation<Z> appliedTransformation = null;
    Resource<Z> transformed = decoded;
    // 如果不是从磁盘缓存中获取的,则需要对资源进行转换
    if (dataSource != DataSource.RESOURCE_DISK_CACHE) {
      appliedTransformation = decodeHelper.getTransformation(resourceSubClass);
      transformed = appliedTransformation.transform(glideContext, decoded, width, height);
    }
    // TODO: Make this the responsibility of the Transformation.
    if (!decoded.equals(transformed)) {
      decoded.recycle();
    }

    final EncodeStrategy encodeStrategy;
    final ResourceEncoder<Z> encoder;
    if (decodeHelper.isResourceEncoderAvailable(transformed)) {
      encoder = decodeHelper.getResultEncoder(transformed);
      encodeStrategy = encoder.getEncodeStrategy(options);
    } else {
      encoder = null;
      encodeStrategy = EncodeStrategy.NONE;
    }

    Resource<Z> result = transformed;

    // 缓存相关
    ...

    return result;
  }

可以看到,这里的任务是对资源进行转换,也就是我们请求的时候如果配置了 centerCrop、fitCenter 等,这里就需要转换成对应的资源。

  • DecodePath#decode() 中的关注点(3)
    关注点(3) transcoder.transcode(transformed, options) 中的 transcoder 为 BitmapDrawableTranscoder,所以这里调用的是 BitmapDrawableTranscoder#transcode():
  /*BitmapDrawableTranscoder*/
  @Override
  public Resource<BitmapDrawable> transcode(
      @NonNull Resource<Bitmap> toTranscode, @NonNull Options options) {
    return LazyBitmapDrawableResource.obtain(resources, toTranscode);
  }

继续往下跟:

  /*LazyBitmapDrawableResource*/
  public static Resource<BitmapDrawable> obtain(
      @NonNull Resources resources, @Nullable Resource<Bitmap> bitmapResource) {
    if (bitmapResource == null) {
      return null;
    }
    return new LazyBitmapDrawableResource(resources, bitmapResource);
  }

  /*LazyBitmapDrawableResource*/
  private LazyBitmapDrawableResource(
      @NonNull Resources resources, @NonNull Resource<Bitmap> bitmapResource) {
    this.resources = Preconditions.checkNotNull(resources);
    this.bitmapResource = Preconditions.checkNotNull(bitmapResource);
  }

因为 LazyBitmapDrawableResource 实现了 Resource<BitmapDrawable>,所以最后是返回了一个 Resource<BitmapDrawable>,也就是说转码这一步是将 Resource<Bitmap> 转成了 Resource<BitmapDrawable>。

到这里,DecodeJob#decodeFromRetrievedData() 中的关注点(1)解码的流程就走完了,我们回去继续看关注点(2)。

  • DecodeJob#decodeFromRetrievedData() 中的关注点(2)
    这里我再贴一下之前的代码:
  /*DecodeJob*/
  private void decodeFromRetrievedData() {
    Resource<R> resource = null;
    try {
      //(1)解码
      resource = decodeFromData(currentFetcher, currentData, currentDataSource);
    } catch (GlideException e) {
      e.setLoggingDetails(currentAttemptingKey, currentDataSource);
      throwables.add(e);
    }
    if (resource != null) {
      //(2)解码完成,通知下去
      notifyEncodeAndRelease(resource, currentDataSource);
    } else {
      runGenerators();
    }
  }

刚刚关注点(1)的解码过程已经完成,现在需要通知下去了,点击 notifyEncodeAndRelease() 方法进去看看:

  /*DecodeJob*/
  private void notifyEncodeAndRelease(Resource<R> resource, DataSource dataSource) {
    if (resource instanceof Initializable) {
      ((Initializable) resource).initialize();
    }

    Resource<R> result = resource;
    LockedResource<R> lockedResource = null;
    if (deferredEncodeManager.hasResourceToEncode()) {
      lockedResource = LockedResource.obtain(resource);
      result = lockedResource;
    }

    // (1)通知外面已经完成了
    notifyComplete(result, dataSource);

    stage = Stage.ENCODE;
    try {
      if (deferredEncodeManager.hasResourceToEncode()) {
        // 将资源缓存到磁盘
        deferredEncodeManager.encode(diskCacheProvider, options);
      }
    } finally {
      if (lockedResource != null) {
        lockedResource.unlock();
      }
    }
    // Call onEncodeComplete outside the finally block so that it's not called if the encode process
    // throws.
    // 完成,释放各种资源
    onEncodeComplete();
  }

点击关注点(1)进去看看:

  /*DecodeJob*/
  private void notifyComplete(Resource<R> resource, DataSource dataSource) {
    setNotifiedOrThrow();
    callback.onResourceReady(resource, dataSource);
  }

这里的 callback 只有一个实现类就是 EngineJob,所以直接看 EngineJob#onResourceReady():

  /*EngineJob*/
  @Override
  public void onResourceReady(Resource<R> resource, DataSource dataSource) {
    synchronized (this) {
      this.resource = resource;
      this.dataSource = dataSource;
    }
    // 通知结果回调
    notifyCallbacksOfResult();
  }

继续跟进:

  /*EngineJob*/
  void notifyCallbacksOfResult() {
    ResourceCallbacksAndExecutors copy;
    Key localKey;
    EngineResource<?> localResource;
    synchronized (this) {
      stateVerifier.throwIfRecycled();
      // 如果取消,则回收和释放资源
      if (isCancelled) {
        resource.recycle();
        release();
        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, key, resourceListener);
      hasResource = true;
      copy = cbs.copy();
      incrementPendingCallbacks(copy.size() + 1);

      localKey = key;
      localResource = engineResource;
    }

    //(1)
    engineJobListener.onEngineJobComplete(this, localKey, localResource);

    //(2)
    for (final ResourceCallbackAndExecutor entry : copy) {
      entry.executor.execute(new CallResourceReady(entry.cb));
    }
    decrementPendingCallbacks();
  }

这里标记了 2 个关注点,分别如下:

  • EngineJob#notifyCallbacksOfResult() 中的关注点(1)
    这里表示 EngineJob 完成了,回调给 Engine,进入 onEngineJobComplete() 看看:
  /*Engine*/
  @Override
  public synchronized void onEngineJobComplete(
      EngineJob<?> engineJob, Key key, EngineResource<?> resource) {
    // A null resource indicates that the load failed, usually due to an exception.
    if (resource != null && resource.isMemoryCacheable()) {
      activeResources.activate(key, resource);
    }

    jobs.removeIfCurrent(key, engineJob);
  }

  /*ActiveResources*/
  synchronized void activate(Key key, EngineResource<?> resource) {
    ResourceWeakReference toPut =
        new ResourceWeakReference(
            key, resource, resourceReferenceQueue, isActiveResourceRetentionAllowed);

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

这里主要判断是否配置了内存缓存,有的话就存到活动缓存中。

  • EngineJob#notifyCallbacksOfResult() 中的关注点(2)
    我这里再贴一下 notifyCallbacksOfResult() 方法中与关注点(2)有关的代码:
  /*EngineJob*/
  void notifyCallbacksOfResult() {
    ResourceCallbacksAndExecutors copy;
    synchronized (this) {
      copy = cbs.copy();
    }
    //(2)
    for (final ResourceCallbackAndExecutor entry : copy) {
      entry.executor.execute(new CallResourceReady(entry.cb));
    }
  }

可以看到,这里遍历 copy 后拿到了线程池的执行器(entry.executor),copy 是上面一行 copy = cbs.copy(); 得到的,我们利用反推看下这个线程池的执行器是怎么来的:

    // 1. cbs.copy()
    /*ResourceCallbacksAndExecutors*/
    ResourceCallbacksAndExecutors copy() {
      return new ResourceCallbacksAndExecutors(new ArrayList<>(callbacksAndExecutors));
    }

    // 2. callbacksAndExecutors 集合是哪里添加元素的
    /*ResourceCallbacksAndExecutors*/
    void add(ResourceCallback cb, Executor executor) {
      callbacksAndExecutors.add(new ResourceCallbackAndExecutor(cb, executor));
    }

  // 3. 上面的 add() 方法是哪里调用的
  /*EngineJob*/
  synchronized void addCallback(final ResourceCallback cb, Executor callbackExecutor) {
    cbs.add(cb, callbackExecutor);
  }

  // 4. 上面的 addCallback() 方法是哪里调用的
  /*Engine*/
  private <R> LoadStatus waitForExistingOrStartNewJob(
      ...
      Executor callbackExecutor,
      ...
      ) {

    engineJob.addCallback(cb, callbackExecutor);
    return new LoadStatus(cb, engineJob);
  }

这里我们反推了 4 步,发现是从 waitForExistingOrStartNewJob() 方法那里传进来的,继续往后推的代码就不列出来了,最后发现是从 into() 方法哪里传过来的(可以自己正序再跟踪一遍源码):

  /*RequestBuilder*/
  public ViewTarget<ImageView, TranscodeType> into(@NonNull ImageView view) {

    ...

    return into(
        glideContext.buildImageViewTarget(view, transcodeClass),
        /*targetListener=*/ null,
        requestOptions,
        Executors.mainThreadExecutor());
  }

也就是这里的 Executors.mainThreadExecutor(),点进去看看是什么:

public final class Executors {

  private static final Executor MAIN_THREAD_EXECUTOR =
      new Executor() {
        private final Handler handler = new Handler(Looper.getMainLooper());

        @Override
        public void execute(@NonNull Runnable command) {
          handler.post(command);
        }
      };

  /** Posts executions to the main thread. */
  public static Executor mainThreadExecutor() {
    return MAIN_THREAD_EXECUTOR;
  }
}

原来这里是创建了一个 Executor 的实例,然后重写了 execute() 方法,但是里面却用的是主线程中的 Handler 来 post() 一个任务,也就是切换到了主线程去执行了。

再回到关注点(2),发现执行这一句 entry.executor.execute(new CallResourceReady(entry.cb)) 实际执行的是 handler.post(command),所以 CallResourceReady 中的 run() 方法是在主线程中执行的。真是想不到呀,原来子线程切换到主线程在一开始的 into() 方法中就做了铺垫!

那么我们继续往下看,进入 CallResourceReady#run():

  /*EngineJob*/
  private class CallResourceReady implements Runnable {

    @Override
    public void run() {
      synchronized (cb.getLock()) {
        synchronized (EngineJob.this) {
          if (cbs.contains(cb)) {
            engineResource.acquire();
            // 关注点
            callCallbackOnResourceReady(cb);
            removeCallback(cb);
          }
          decrementPendingCallbacks();
        }
      }
    }
  }

继续跟进:

  /*EngineJob*/
  void callCallbackOnResourceReady(ResourceCallback cb) {
    try {
      // 资源准备好了,回调给上一层
      cb.onResourceReady(engineResource, dataSource);
    } catch (Throwable t) {
      throw new CallbackException(t);
    }
  }

上面会回调到 SingleRequest#onResourceReady(),进去看看:

  /*SingleRequest*/
  @Override
  public void onResourceReady(Resource<?> resource, DataSource dataSource) {
    stateVerifier.throwIfRecycled();
    Resource<?> toRelease = null;
    try {
      synchronized (requestLock) {
        loadStatus = null;
        if (resource == null) {
          GlideException exception =
              new GlideException(...);
          onLoadFailed(exception);
          return;
        }

        Object received = resource.get();
        if (received == null || !transcodeClass.isAssignableFrom(received.getClass())) {
          toRelease = resource;
          this.resource = null;
          GlideException exception =
              new GlideException(...);
          onLoadFailed(exception);
          return;
        }

        if (!canSetResource()) {
          toRelease = resource;
          this.resource = null;
          status = Status.COMPLETE;
          return;
        }

        // 关注点
        onResourceReady((Resource<R>) resource, (R) received, dataSource);
      }
    } finally {
      if (toRelease != null) {
        engine.release(toRelease);
      }
    }
  }

可以看到,前面是一些加载失败的判断,看下最后的 onResourceReady():

  /*SingleRequest*/
  private void onResourceReady(Resource<R> resource, R result, DataSource dataSource) {

    ...

    try {
      boolean anyListenerHandledUpdatingTarget = false;
      if (requestListeners != null) {
        for (RequestListener<R> listener : requestListeners) {
          anyListenerHandledUpdatingTarget |=
              listener.onResourceReady(result, model, target, dataSource, isFirstResource);
        }
      }
      anyListenerHandledUpdatingTarget |=
          targetListener != null
              && targetListener.onResourceReady(result, model, target, dataSource, isFirstResource);

      if (!anyListenerHandledUpdatingTarget) {
        Transition<? super R> animation = animationFactory.build(dataSource, isFirstResource);
        // 回调给 ImageViewTarget
        target.onResourceReady(result, animation);
      }
    } finally {
      isCallingCallbacks = false;
    }

    // 通知加载成功
    notifyLoadSuccess();
  }

这里的 target 为 ImageViewTarget,进入 ImageViewTarget#onResourceReady() 看看:

  /*ImageViewTarget*/
  @Override
  public void onResourceReady(@NonNull Z resource, @Nullable Transition<? super Z> transition) {
    if (transition == null || !transition.transition(resource, this)) {
      setResourceInternal(resource);
    } else {
      maybeUpdateAnimatable(resource);
    }
  }

  /*ImageViewTarget*/
  private void setResourceInternal(@Nullable Z resource) {
    setResource(resource);
    maybeUpdateAnimatable(resource);
  }

因为在前面 "2.3.1 GlideContext#buildImageViewTarget()" 中创建的 ImageViewTarget 的实现类是 DrawableImageViewTarget,所以这里调用的是 DrawableImageViewTarget#setResource(),点进去看看:

  /*DrawableImageViewTarget*/
  @Override
  protected void setResource(@Nullable Drawable resource) {
    view.setImageDrawable(resource);
  }

到这里终于将图片显示到我们的 ImageView 中了!into() 方法也结束了。

2.3.4 小结

要我总结的话,只能说 into() 方法实在是太复杂了,with() 与 load() 方法在它面前就是小喽喽。
into() 方法主要做了发起网络请求、缓存数据、解码并显示图片。

大概流程为:
发起网络请求前先判断是否有内存缓存,有则直接从内存缓存那里获取数据进行显示,没有则判断是否有磁盘缓存;有磁盘缓存则直接从磁盘缓存那里获取数据进行显示,没有才发起网络请求;网络请求成功后将返回的数据存储到内存与磁盘缓存(如果有配置),最后将返回的输入流解码成 Drawable 显示在 ImageView 上。

三、总结

Glide 源码相对于我之前写的其他源码文章来说确实难啃,但是耐心看完发现收获也很多。例如利用一个隐藏的 Fragment 来管理 Glide 请求的生命周期,利用四级缓存来提升加载图片的效率,还有网络请求成功后是在哪里切换到主线程的等等。

参考资料:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,547评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,399评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,428评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,599评论 1 274
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,612评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,577评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,941评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,603评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,852评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,605评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,693评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,375评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,955评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,936评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,172评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,970评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,414评论 2 342