github编辑

Glide源码分析

Glide的使用非常简单只需要调用withload into三个方法。

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

接下来,我们依次分析这三个方法。

with()

//Glide.java
public static RequestManager with(@NonNull Activity activity) {
  //先获取RequestManagerRetriever对象
  //调用RequestManagerRetriever的get方法获取RequestManager
  return getRetriever(activity).get(activity); 
}
private static RequestManagerRetriever getRetriever(@Nullable Context context) {
  // Context could be null for other reasons (ie the user passes in null), but in practice it will
  // only occur due to errors with the Fragment lifecycle.
  Preconditions.checkNotNull(
      context,
      "You cannot start a load on a not yet attached View or a Fragment where getActivity() "
          + "returns null (which usually occurs when getActivity() is called before the Fragment "
          + "is attached or after the Fragment is destroyed).");
  
  return Glide.get(context).getRequestManagerRetriever();
}

get()

ApiGlideModule

ApiGlideModule定义了在应用程序中初始化 Glide 时要使用的一系列依赖关系和选项。

checkAndInitializeGlide()

initializeGlide()

GlideBuilder

GlideExecutor

build()中一共创建了4个线程池

newDiskCacheExecutor()创建磁盘缓存的线程池

其余三个线程池都是负责下载和解码的newAnimationBuilder是用来处理gif的。

这三个线程池选用哪个呢?

useUnlimitedSourceGeneratorsPooluseAnimationPool可以通过BaseRequestOptions进行配置。

useAnimationPool默认不需要配置。系统默认会在处理gif的时候设置为true。

MemorySizeCalculator

磁盘缓存

get()

Lifecycle

Glide会添加一个透明的Fragment,当Fragment执行生命周期方法时,回调Lifecycle注册的LifecycleListener

LifecycleListener

RequestManager

RequestManager中将当前对象和DefaultConnectivityMonitor和注册到Lifecycle

load()

通过with()方法返回了一个RequestManager对象,所以load()方法调用的是RequestManagerload()方法。

RequestBuilder

into()

load()比较简单就是创建一个RequestBuilder对象。into()方法就是调用RequestBuilderinto()

obtainRequest()

Request

整体流程
第一次加载网络图片的编解码过程

缓存过程

getModelLoaders()

加载到内存的图片大小

默认大小为ImageView的大小。设置了override,则是设置的大小。如果设置值为Target.SIZE_ORIGINAL,则使用图片原始大小。

参考

最后更新于