Glide源码解析一——Glide、Registry相关

2022-06-16  本文已影响0人  GIndoc

ps:以下源码分析基于Glide v4.11.0

Glide.jpg

涉及的类

主要涉及到以下这些类:

  1. Glide,全局唯一
  2. RequestManagerRetriever,用于获取RequestManager
  3. RequestManagerFragment/SupportRequestManagerFragment,用于提供生命周期
  4. RequestManager,用于管理Request,内部使用RequestTracker控制Reqeust的开始、暂停等
  5. RequestTracker,控制Reqeust的开始、暂停等
  6. Request,对应着每一个图片请求

数据处理的类型

  1. Model:输入类型,例如请求的url、某个图片文件、资源drawableId等等。可以参考Engine的构造函数中,Registry#append(...)添加的类型。
  2. Data/DataClass:数据源返回的类型,例如InputStream、ParcelFileDescriptor、File、ByteBuffer等。可以参考Engine的构造函数中,Registry#append(...)添加的类型。
  3. Resource/ResourceType/TResource:中间类型,从数据源返回的类型Data编码成的类型,例如Bitmap、Drawable、GifDrawable、BitmapDrawable、File等。举个例子:例如由InputStream编码成Bitmap。可以参考Engine的构造函数中,Registry#append(...)添加的类型。
  4. transcode:最终返回的类型。从Resource转换成的类型,例如BitmapDrawable、byte[]。举个例子:由Bitmap转换成BitmapDrawable、由Bitmap转换成byte[]。可以参考Engine的构造函数中,Registry#register(...)添加的类型。

从使用方法作为入口进行分析:

Glide.with(activity)
    .load(url)
    .into(targetView);

Glide

Glide,是全局唯一的,当我们调用Glide#get(context)时,会去判断是否已经实例化,没有的话会实例化。

// Glide.java
public static RequestManager with(@NonNull View view) {
    return getRetriever(view.getContext()).get(view);
}
  
@NonNull
private static RequestManagerRetriever getRetriever(@Nullable Context context) {
    ...
    return Glide.get(context).getRequestManagerRetriever();
}

public static Glide get(@NonNull Context context) {
    if (glide == null) {
    
      // 获取@GlideModule生成的GeneratedAppGlideModuleImpl类
      GeneratedAppGlideModule annotationGeneratedModule =
          getAnnotationGeneratedGlideModules(context.getApplicationContext());
      synchronized (Glide.class) {
        if (glide == null) {
          // 实例化Glide
          checkAndInitializeGlide(context, annotationGeneratedModule);
        }
      }
    }

    return glide;
}


private static void checkAndInitializeGlide(
      @NonNull Context context, @Nullable GeneratedAppGlideModule generatedAppGlideModule) {
    
    if (isInitializing) {
      throw new IllegalStateException(
          "...");
    }
    isInitializing = true;
    initializeGlide(context, generatedAppGlideModule);
    isInitializing = false;
}


private static void initializeGlide(
      @NonNull Context context, @Nullable GeneratedAppGlideModule generatedAppGlideModule) {
    initializeGlide(context, new GlideBuilder(), generatedAppGlideModule);
}


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()) {
      // 解析Manifest中注册的自定义的GlideModule
      manifestModules = new ManifestParser(applicationContext).parse();
    }

    // ... 省略一些GlideModule和log相关的代码

    RequestManagerRetriever.RequestManagerFactory factory =
        annotationGeneratedModule != null
            ? annotationGeneratedModule.getRequestManagerFactory()
            : null;
            
    // 设置RequestManagerFactory,后面用于创建RequestManager
    // 如果没有@GlideModule生成的GeneratedAppGlideModuleImpl类,即factory为null,则使用RequestManagerRetriever类中的一个默认Factory
    builder.setRequestManagerFactory(factory);
    
    // ... 省略应用GlideModule相关代码
    
    Glide glide = builder.build(applicationContext);
    
    // ... 省略应用GlideModule相关代码
    
    Glide.glide = glide;
}

Glide(
      @NonNull Context context,
      @NonNull Engine engine,
      @NonNull MemoryCache memoryCache,
      @NonNull BitmapPool bitmapPool,
      @NonNull ArrayPool arrayPool,
      @NonNull RequestManagerRetriever requestManagerRetriever,
      @NonNull ConnectivityMonitorFactory connectivityMonitorFactory,
      int logLevel,
      @NonNull RequestOptionsFactory defaultRequestOptionsFactory,
      @NonNull Map<Class<?>, TransitionOptions<?, ?>> defaultTransitionOptions,
      @NonNull List<RequestListener<Object>> defaultRequestListeners,
      boolean isLoggingRequestOriginsEnabled,
      boolean isImageDecoderEnabledForBitmaps) {
      
    this.engine = engine;
    
    // bitmap对象池
    this.bitmapPool = bitmapPool;
    
    // 数组对象池
    this.arrayPool = arrayPool;
    
    // 默认是LruResourceCache
    this.memoryCache = memoryCache;
    
    // 用于根据参数(Application、Activity、FragmentActivity、Fragment、View)获取RequestManager,详见RequestManagerRetriever章节
    this.requestManagerRetriever = requestManagerRetriever;
    
    // 内置了一系列的Entry,包含了ModelClass、DataClass、TransocdeClass、Encoder、Decoder、Transcoder等
    registry = new Registry();
    
    // Decoder
    ResourceDecoder<ByteBuffer, Bitmap> byteBufferBitmapDecoder;
    ResourceDecoder<InputStream, Bitmap> streamBitmapDecoder;
    if (isImageDecoderEnabledForBitmaps && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
      streamBitmapDecoder = new InputStreamBitmapImageDecoderResourceDecoder();
      byteBufferBitmapDecoder = new ByteBufferBitmapImageDecoderResourceDecoder();
    } else {
      byteBufferBitmapDecoder = new ByteBufferBitmapDecoder(downsampler);
      streamBitmapDecoder = new StreamBitmapDecoder(downsampler, arrayPool);
    }
    
    // 创建ModelLoader的Factory,这里的StreamFactory创建的的是ModelLoader的子类ResourceLoader
    ResourceLoader.StreamFactory resourceLoaderStreamFactory =
        new ResourceLoader.StreamFactory(resources);
        
    // Transcoder
    BitmapBytesTranscoder bitmapBytesTranscoder = new BitmapBytesTranscoder();
    
    // 注册Encoder
    registry
        .append(ByteBuffer.class, new ByteBufferEncoder())
        .append(InputStream.class, new StreamEncoder(arrayPool));
    
    // 注册Decoder
    registry.append(Registry.BUCKET_BITMAP, ByteBuffer.class, Bitmap.class, byteBufferBitmapDecoder);
    
    // 注册创建ModelLoader的Factory
    registry
        .append(int.class, InputStream.class, resourceLoaderStreamFactory)
        
    ...
    
    // 根据TranscodeClass创建ImageViewTarget的工厂类
    ImageViewTargetFactory imageViewTargetFactory = new ImageViewTargetFactory();
    
    // 用于之后获取Registry等对象
    glideContext =
        new GlideContext(
            context,
            arrayPool,
            registry,
            imageViewTargetFactory,
            defaultRequestOptionsFactory,
            defaultTransitionOptions,
            defaultRequestListeners,
            engine,
            isLoggingRequestOriginsEnabled,
            logLevel);
      
}
// GlideBuilder.java
Glide build(@NonNull Context context) {
    
    ...
    
    // 用来获取RequestManager对象(内部使用RequestManagerFactory创建RequestManager)
    RequestManagerRetriever requestManagerRetriever =
        new RequestManagerRetriever(requestManagerFactory);
        
    ...
    
    return new Glide(
        context,
        engine,
        memoryCache,
        bitmapPool,
        arrayPool,
        requestManagerRetriever,
        connectivityMonitorFactory,
        logLevel,
        defaultRequestOptionsFactory,
        defaultTransitionOptions,
        defaultRequestListeners,
        isLoggingRequestOriginsEnabled,
        isImageDecoderEnabledForBitmaps);
}

上一篇下一篇

猜你喜欢

热点阅读