Glide源码粘贴

本文转自享学课堂derry

 

一、Glide基本使用

Glide.with(this).load(URL).into(imageView)

二、Glide源码----with

with的源码接受了不同的参数。最终返回了RequestManager

 @NonNull
  public static RequestManager with(@NonNull Activity activity) {
    return getRetriever(activity).get(activity);
  }

  @NonNull
  public static RequestManager with(@NonNull FragmentActivity activity) {
    return getRetriever(activity).get(activity);
  }
  @NonNull
  public static RequestManager with(@NonNull Fragment fragment) {
    return getRetriever(fragment.getActivity()).get(fragment);
  }
  @Deprecated
  @NonNull
  public static RequestManager with(@NonNull android.app.Fragment fragment) {
    return getRetriever(fragment.getActivity()).get(fragment);
  }
 @NonNull
  public static RequestManager with(@NonNull View view) {
    return getRetriever(view.getContext()).get(view);
  }

其大概的思路如下,一个是底层的,一个是新建的

对上图的总结:

一共分为两种:第一种是作用域Application,它的生命周期是全局的,不搞空白Fragment就绑定Activity/Fragment

第二种是作用域非Application,它的生命周期是,专门搞空白Fragment就绑定Activity/Fragment

作用域分析

1、Application作用域源码分析(Application 域请求管理)RequestManagerRetriever.java:

在get方法里。有各种不同的返回,最终非application的将会走到各自的get方法里,application的会走getApplicationManager

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

    return getApplicationManager(context);
  }
  @NonNull
  private RequestManager getApplicationManager(@NonNull Context context) {
    // Either an application context or we're on a background thread.
    if (applicationManager == null) {
      synchronized (this) {
        if (applicationManager == null) {
          Glide glide = Glide.get(context.getApplicationContext());
          applicationManager =
              factory.build(
                  glide,
                  new ApplicationLifecycle(),
                  new EmptyRequestManagerTreeNode(),
                  context.getApplicationContext());
        }
      }
    }

    return applicationManager;
  }

主要关注以下两点:

第一点:Application 域对应的是 applicationManager,它是与RequestManagerRetriever 对象绑定的

第二点:在子线程调用 get(...) ,或者传入参数是 ApplicationContext &ServiceContext 时,对应的请求是Application域

2、Activity作用域源码分析

  @NonNull
  public RequestManager get(@NonNull FragmentActivity activity) {
    if (Util.isOnBackgroundThread()) {
      return get(activity.getApplicationContext());
    } else {
      assertNotDestroyed(activity);
      FragmentManager fm = activity.getSupportFragmentManager();
      return supportFragmentGet(
          activity, fm, /*parentHint=*/ null, isActivityVisible(activity));
    }
  }
可以看到,第一个函数是不是获得了 FragmentActivity 的FragmentManager,之后调用 supportFragmentGet(...) 获得RequestManager。

3.Fragment作用域源码分析,RequestManagerRetriever.java

  @NonNull
  public RequestManager get(@NonNull Fragment fragment) {
    Preconditions.checkNotNull(fragment.getActivity(),
          "You cannot start a load on a fragment before it is attached or after it is destroyed");
    if (Util.isOnBackgroundThread()) {
      return get(fragment.getActivity().getApplicationContext());
    } else {
      FragmentManager fm = fragment.getChildFragmentManager();
      return supportFragmentGet(fragment.getActivity(), fm, fragment, fragment.isVisible());
    }
  }
可以看到,这里先获得了 Fragment 的FragmentManager ( getChildFragmentManager() ) ,之后调用supportFragmentGet(...) 获得RequestManager
 

 

 

Activity/Fragment/FragmentActivity作用域属于一类 都是一样的 都会搞一个空白的 Fragment去监听Activity/Fragment/FragmentActivity, Application作用域是另外 一类,不会搞空白的Fragment去监听;

 

 

生命周期的绑定

 

在上面的分析我们已经得知Activity 域和 Fragment 域都会调用 supportFragmentGet(...) 来获得 RequestManager,那么就专门分析这个方法吧 RequestManagerRetriever.java:

SupportRequestManagerFragment其实就是封装了lifecycle的

  @NonNull
  private RequestManager supportFragmentGet(
      @NonNull Context context,
      @NonNull FragmentManager fm,
      @Nullable Fragment parentHint,
      boolean isParentVisible) {
// 1、从 FragmentManager 中获取 SupportRequestManagerFragment
    SupportRequestManagerFragment current =
        getSupportRequestManagerFragment(fm, parentHint, isParentVisible);
//2、从该 Fragment 中获取 RequestManager
    RequestManager requestManager = current.getRequestManager();
//3、首次获取,则实例化 RequestManager
    if (requestManager == null) {
      // TODO(b/27524013): Factor out this Glide.get() call.
// 3.1 实例化
      Glide glide = Glide.get(context);
//3.2 设置 Fragment 对应的 RequestMananger
      requestManager =
          factory.build(
              glide, current.getGlideLifecycle(), current.getRequestManagerTreeNode(), context);
      current.setRequestManager(requestManager);
    }
    return requestManager;
  }
//1、从 FragmentManager 中获取 SupportRequestManagerFragment
 @NonNull
  private SupportRequestManagerFragment getSupportRequestManagerFragment(
      @NonNull final FragmentManager fm, @Nullable Fragment parentHint, boolean isParentVisible) {
//1.1 尝试获取 FRAGMENT_TAG 对应的 Fragment
    SupportRequestManagerFragment current =
        (SupportRequestManagerFragment) fm.findFragmentByTag(FRAGMENT_TAG);
// 1.2 尝试从临时记录中获取 Fragment
    if (current == null) {
      current = pendingSupportRequestManagerFragments.get(fm);
// 1.3 实例化 Fragment
      if (current == null) {
//1.3.1 创建对象
        current = new SupportRequestManagerFragment();
        current.setParentFragmentHint(parentHint);
// 1.3.2 如果父层可见,则调用 onStart() 生命周期
        if (isParentVisible) {
          current.getGlideLifecycle().onStart();
        }
// 1.3.3 临时记录映射关系
        pendingSupportRequestManagerFragments.put(fm, current);
// 1.3.4 提交 Fragment 事务
        fm.beginTransaction().add(current, FRAGMENT_TAG).commitAllowingStateLoss();
//  1.3.5 post 一个消息
        handler.obtainMessage(ID_REMOVE_SUPPORT_FRAGMENT_MANAGER, fm).sendToTarget();
      }
    }
    return current;
  }

上面三段代码中,重点关心下面三点:

 

第一点:从 FragmentManager 中获取 SupportRequestManagerFragment;

第二点:从该 Fragment 中获取 RequestManager;

第三点:首次获取,则实例化 RequestManager,后续从同一个 SupportRequestManagerFragment 中都获取的是这个 RequestManager;

整个的关键核心在 getSupportRequestManagerFragment函数:

第一步:尝试获取FRAGMENT_TAG对应的fragment

 

第二步:尝试从临时记录中获取 Fragment

 

第三步:实例化 Fragment

 ·第一点: 创建对象

· 第二点:如果父层可见,则调用 onStart() 生命周期

· 第三点:临时记录映射关系

· 第四点:提交 Fragment 事务

· 第五点:post 一个消息

·第六点:移除临时记录中的映射关系

会发现上面的【记录保存】 比较难理解,为什么难理解? 因为在提交 Fragment 事务之前,为什么需要先保存记录?

就是为了避免 SupportRequestManagerFragment 在一个作用域中重复创建。

commitAllowingStateLoss是将事务 post 到消息队列中的,也就是说,事 务是异步处理的,而不是同步处理的。假设没有临时保存记录,一旦在事务异步等待 执行时调用了Glide.with(),就会在该作用域中重复创建 Fragment。

生命周期的监听机制

通过上面的学习,已经明白框架为每个Activity 和 Fragment 作用域创建了 一个无UI的Fragment,而现在我们来分析 Glide 如何监听这个无界面 Fragment 的 生命周期的 SupportRequestManagerFragment.java:

  @NonNull
  ActivityFragmentLifecycle getGlideLifecycle() {
    return lifecycle;
  }
class ActivityFragmentLifecycle implements Lifecycle {
  private final Set<LifecycleListener> lifecycleListeners =
      Collections.newSetFromMap(new WeakHashMap<LifecycleListener, Boolean>());
  private boolean isStarted;
  private boolean isDestroyed;

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

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

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

}

RequestManagerRetriever.java 源码的分析:

  Glide glide = Glide.get(context);
      requestManager =
          factory.build(
              glide, current.getGlideLifecycle(), current.getRequestManagerTreeNode(), context);
      current.setRequestManager(requestManager);

实际上返回了Requestmanager对象

//RequestManager 工厂接口
public interface RequestManagerFactory {
    @NonNull
    RequestManager build(
        @NonNull Glide glide,
        @NonNull Lifecycle lifecycle,
        @NonNull RequestManagerTreeNode requestManagerTreeNode,
        @NonNull Context context);
  }
//默认 RequestManager 工厂接口实现类
  private static final RequestManagerFactory DEFAULT_FACTORY = new RequestManagerFactory() {
    @NonNull
    @Override
    public RequestManager build(@NonNull Glide glide, @NonNull Lifecycle lifecycle,
        @NonNull RequestManagerTreeNode requestManagerTreeNode, @NonNull Context context) {
      return new RequestManager(glide, lifecycle, requestManagerTreeNode, context);
    }
  };

RequestManager.java 源码的分析:

final Lifecycle lifecycle;

RequestManager(Glide glide, Lifecycle lifecycle, ...){
    ...
    this.lifecycle = lifecycle;
    
    添加监听
    lifecycle.addListener(this);
}

@Override public synchronized void onDestroy() {
    ...
    移除监听
    lifecycle.removeListener(this); }

可以看到,实例化 RequestManager 时需要一个 Lifecycle对象,这个对象是 在无界面 Fragment 中创建的,当 Fragment 的生命周期变化时,就是通过这个 Lifecycle 对象将事件分发到 RequestManager

生命周期的回调

我们来看 RequestManager 收到生命周期回调后的处理:

public interface LifecycleListener {
    void onStart();
    void onStop();
    void onDestroy();
}

总结:

glide通过with创建了RequestManagerRetriever对象

RequestManagerRetriever可以通过不同的上下文对象区分获取RequestManager

作用域的就直接在主线程进行生命周期的绑定,使用fragmentGet 传入glide、lifecycle给RequestManager进行生命周期监听,

非作用域的就新建空白SupportRequestManagerFragment进行生命周期的绑定监听,通过supportFragmentGet  传入glide、lifecycle给RequestManager进行生命周期监听,

至此,完成了对空白以及非空白页面的监听逻辑

with源码

各个类的作用

Glide

主要做一些 init 工作,比如缓存,线程池,复用池的构建等等。

RequestManagerRetriever

主要是获得一个RequestManager请求管理类,然后绑定一个 Fragment 。

SupportRequestManagerFragment :

用于管理请求的生命周期。

RequestManager

主要用于对请求的管理封装。

流程:

第一步:调用 with,可以看下 with 这个源码函数,重载有很多:

上面其实常用的就 Activity,Fragment, Context 这 3 种形式,下面我们就以Activity 为主

第二步,getRetriever(activity):

 @NonNull
    public static Glide get(@NonNull Context context) {
        if (glide == null) {
            Class var1 = Glide.class;
            synchronized(Glide.class) {
                if (glide == null) {
                    checkAndInitializeGlide(context);
                }
            }
        }

        return glide;
    }

Glide get(Context) 是一种双重检测单例模式(DCL),保证了多线程下安全,仅此而已,非常的简单:

checkAndInitializeGlide(context); 看看做了什么:

private static void checkAndInitializeGlide(@NonNull Context context) {
    if (isInitializing) {
        //这里会抛出初始化异常的 信息
    } else {
        //是否初始化标志
        isInitializing = true;
        //开始进行初始化
        initializeGlide(context);
        isInitializing = false;
    }
}

  private static void initializeGlide(@NonNull Context context) {
        //实例化一个 GlideBuilder 在进行初始化
        //GlideBuilder 默认的一些配置信息
        initializeGlide(context, new GlideBuilder());
    }
private static void initializeGlide(@NonNull Context context, @NonNull GlideBuilder builder) {
        //1. 拿到应用级别的上下文,这里可以避免内存泄漏,我们实际开发也可以通 过这种形式拿上下文。
        Context applicationContext = context.getApplicationContext();
        //2. 这里拿到 @GlideModule 标识的注解处理器生成的 GeneratedAppGlideModuleImpl、                                   //GeneratedAppGlideModuleFactory ...等等。
        GeneratedAppGlideModule annotationGeneratedModule = getAnnotationGeneratedGlideModules();

      . ....

        //3. 通过注解生成的代码拿到 RequestManagerFactory
        RequestManagerFactory factory = annotationGeneratedModule != null ?                                          annotationGeneratedModule.getRequestManagerFactory() : null;
        //4. 将拿到的工厂添加到 GlideBuilder 
        builder.setRequestManagerFactory(factory);
       
      ....
        //5. 这里通过 Builder 建造者模式,构建出 Glide 实例对象
        Glide glide = builder.build(applicationContext);
        Iterator var13 = manifestModules.iterator();

        //6. 开始注册组件回调
        while(var13.hasNext()) {
            GlideModule module = (GlideModule)var13.next();
            module.registerComponents(applicationContext, glide, glide.registry);
        }

        if (annotationGeneratedModule != null) {
           annotationGeneratedModule.registerComponents(applicationContext, glide, glide.registry);
        }
                
        applicationContext.registerComponentCallbacks(glide);
        //将构建出来的 glide 赋值给 Glide 的静态变量
        Glide.glide = glide;
    }

在GlideBuilder里

builder 主要构建线程池、复用池、缓存策略、执行 Engine,最后构建 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 RequestOptions defaultRequestOptions,
      @NonNull Map<Class<?>, TransitionOptions<?, ?>> defaultTransitionOptions,
      @NonNull List<RequestListener<Object>> defaultRequestListeners,
      boolean isLoggingRequestOriginsEnabled) {
    //将 Builder 构建的线程池,对象池,缓存池保存到 Glide 中
    this.engine = engine;
    this.bitmapPool = bitmapPool;
    this.arrayPool = arrayPool;
    this.memoryCache = memoryCache;
    this.requestManagerRetriever = requestManagerRetriever;
    this.connectivityMonitorFactory = connectivityMonitorFactory;
        
    //拿到 Glide 对应需要的编解码
    DecodeFormat decodeFormat = defaultRequestOptions.getOptions().get(Downsampler.DECODE_FORMAT) ;
    bitmapPreFiller = new BitmapPreFiller(memoryCache, bitmapPool, decodeFormat);

    final Resources resources = context.getResources();

    registry = new Registry();
    registry.register(new DefaultImageHeaderParser());
    
  //忽略一些配置信息
  ...
        //用于显示对应图片的工厂
    ImageViewTargetFactory imageViewTargetFactory = new ImageViewTargetFactory();
  
  //构建一个 Glide 专属的 上下文
    glideContext =
        new GlideContext(
            context,
            arrayPool,
            registry,
            imageViewTargetFactory,
            defaultRequestOptions,
            defaultTransitionOptions,
            defaultRequestListeners,
            engine,
            isLoggingRequestOriginsEnabled,
            logLevel);
  }

到这里我们已经知道了 缓存策略、Glide、GlideContext 怎么构建出来的了, 下面我们看怎么拿到请求管理类RequestManager

getRetriever(activity).get(activity); 最终是返回 RequestManager:这里的 get 也有很多重载的函数,在Activity 参数的重载里可以获取到RequestManager,上面的代码已经贴过了

with之后,最终返回RequestManager对象, 我们需要对 RequestManager对象的构建,有一个来龙去脉的学习:

// 此工厂就是为了构建出 RequestManager对象 
 private static final RequestManagerFactory DEFAULT_FACTORY = new RequestManagerFactory() {
    @NonNull
    @Override
    public RequestManager build(@NonNull Glide glide, @NonNull Lifecycle lifecycle,
        @NonNull RequestManagerTreeNode requestManagerTreeNode, @NonNull Context context) {
      //实例化
      return new RequestManager(glide, lifecycle, requestManagerTreeNode, context);
    }
  };

你只要敢 new RequestManager(....); 就会进入 RequestManager的构造方法:

它实现的是 Glide 中的 Lifecycle 生命周期接口,注册是在 刚刚我们讲解 RequestManagerFactory 工厂中实例化的 RequestManager 然后在 构造函数中添加了生命周期回调监听,完成了对生命周期的监听

with总结:

根据 with 源码分析,我们知道,Glide.with(Activity) 主要做了 线程池 + 缓存 + 请求管理与生命周期绑定+其它配置初始化的构建,内部的代码其实是很庞大的

环节二,load 源码:

load的时序图

RequestBuilder : 这是一个通用请求构建类,可以处理通用资源类型的设置选项 和启动负载。

同学们:load 函数加载相对于比较简单。我们看下具体代码实现

  public RequestBuilder<Drawable> load(@Nullable Bitmap bitmap) {
    return asDrawable().load(bitmap);
  }
  public RequestBuilder<Drawable> load(@Nullable Drawable drawable) {
    return asDrawable().load(drawable);
  }
 public RequestBuilder<Drawable> load(@Nullable String string) {
    return asDrawable().load(string);
  }
  public RequestBuilder<Drawable> load(@Nullable Uri uri) {
    return asDrawable().load(uri);
  }
public RequestBuilder<Drawable> load(@RawRes @DrawableRes @Nullable Integer resourceId) {
    return asDrawable().load(resourceId);
  }


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

看一下load的详情

RequestBuilder:

public class RequestBuilder<TranscodeType> extends BaseRequestOptions<RequestBuilder<TranscodeType>>
    implements Cloneable, 
ModelTypes<RequestBuilder<TranscodeType>> {
        
  public RequestBuilder<TranscodeType> load(@Nullable String string) {
    return loadGeneric(string);
  }
  
  // 描述加载的数据源-这里可以看做是我们刚刚传递进来的 http://xxxx.png
  @Nullable private Object model;
  // 描述这个请求是否已经添加了加载的数据源
  private boolean isModelSet;
  
  private RequestBuilder<TranscodeType> loadGeneric(@Nullable Object model) {
    this.model = model;
    isModelSet = true;
    return this;
  }
}

到这里 RequestBuilder 就构建好了, RequestBuilder构建出来后,都是 为了后面的into啊,也意味着,我们目前为止只是摸到Glide的一点点边而已,

环节三,into 源码:

  @NonNull
  public ViewTarget<ImageView, TranscodeType> into(@NonNull ImageView view) {
    Util.assertMainThread();
    Preconditions.checkNotNull(view);
    // 根据 ImageView 布局中的 scaleType 来重构 requestOptions
    BaseRequestOptions<?> requestOptions = this;
    if (!requestOptions.isTransformationSet()
        && requestOptions.isTransformationAllowed()
        && view.getScaleType() != null) {
      //如果在 xml ImageView 节点中 没有设置 scaleType 那么默认在构造函数 中进行了初始化为   mScaleType = ScaleType.FIT_CENTER;  
      switch (view.getScaleType()) {
       . ....
        case FIT_CENTER:
        case FIT_START:
        case FIT_END:
          //这里用到了克隆(原型设计模式),选择一个 居中合适 显示的方案,同学 们会发现,到处都是设计模式,它不是为了装B哦
          requestOptions = requestOptions.clone().optionalFitCenter();
          break;
       ....
      }
    }
    //调用 into 重载函数,创建一个 ViewTarget
    return into(
        //调用 buildImageViewTarget 构建一个 ImageView 类型的 Target(Bitmap/Drawable)
        glideContext.buildImageViewTarget(view, transcodeClass),
        /*targetListener=*/ null,
        requestOptions,
        Executors.mainThreadExecutor());
  }

上面代码就两大步:

第一步:先拿到当前 ImageView getScaleType 类型的属性,然后重新 clone 一个进 行配置;

第二步:调用 into 重载继续构建;

同学们先来看下 glideContext.buildImageViewTarget 是怎么构建出来 ImageViewTarget 的:

  @NonNull
  public <X> ViewTarget<ImageView, X> buildImageViewTarget(
      @NonNull ImageView imageView, @NonNull Class<X> transcodeClass) {
    //调用 工厂模式 根据 transcodeClass 生成出一个对应的 ImageViewTarget
    return imageViewTargetFactory.buildTarget(imageView, transcodeClass);
  }

public class ImageViewTargetFactory {
  @NonNull
  @SuppressWarnings("unchecked")
  public <Z> ViewTarget<ImageView, Z> buildTarget(@NonNull ImageView view,
      @NonNull Class<Z> clazz) {
    //如果目标的编码类型属于 Bitmap 那么就创建一个 Bitmap 类型的 ImageViewTarget
    if (Bitmap.class.equals(clazz)) {
      return (ViewTarget<ImageView, Z>) new BitmapImageViewTarget(view);
    如果目标的编码类型属于 Drawable 那么就创建一个 Drawable 类型的 ImageViewTarget
    } 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)");
    }
  }
}

上面 生产 Target 的时候注意一下,只要调用了asBitmap 才会执行生产 BitmapImageViewTarget 后面会讲到这个,先有个印 象:

public class DrawableImageViewTarget extends ImageViewTarget<Drawable> {

  public DrawableImageViewTarget(ImageView view) {
    super(view);
  @SuppressWarnings({"unused", "deprecation"})
  @Deprecated
  public DrawableImageViewTarget(ImageView view, boolean waitForLayout) {
    super(view, waitForLayout);
  }

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

从上面代码可以知道 DrawableImageViewTarget 继承的是 ImageViewTarget 重写的 setResource 函数,实现了显示 Drawable 图片的逻辑, 好了,这里先有个印象就行,我们只管主线流程,支线细节先跳读,最后会讲到怎么 调用的。继续 into 重载

  private <Y extends Target<TranscodeType>> Y into(
      @NonNull Y target,
      @Nullable RequestListener<TranscodeType> targetListener,
      BaseRequestOptions<?> options,
      Executor callbackExecutor) {
    Preconditions.checkNotNull(target);
    //这里的 isModelSet 是在 load 的时候赋值为 true 的,所以不会抛异常
    if (!isModelSet) {
      throw new IllegalArgumentException("You must call #load() before calling #into()");
    }
        //为这个 http://xxx.png 生成一个 Glide request 请求
    Request request = buildRequest(target, targetListener, options, callbackExecutor);
        //相当于拿到上一个请求
    Request previous = target.getRequest();
    //下面的几行说明是否与上一个请求冲突,一般不用管 直接看下面 else 判断
    if (request.isEquivalentTo(previous)
        && !isSkipMemoryCacheWithCompletePreviousRequest(options, previous)) {
      request.recycle();
      if (!Preconditions.checkNotNull(previous).isRunning()) {
        previous.begin();
      }
      return target;
    }
        //清理掉目标请求管理
    requestManager.clear(target);
    //重新为目标设置一个 Glide request 请求
    target.setRequest(request);
    //最后是调用 RequestManager 的 track 来执行目标的 Glide request 请 求
    requestManager.track(target, request);

    return target;
  }

以上核心就两个点:

第一点:为 target buildRequest 构建一个 Glide request 请求;

第二点:将构建出来的 Request 交于 RequestManager 来执行;  

来简单的来看下怎么构建的 Request:

  private Request buildRequest(
      Target<TranscodeType> target,
      @Nullable RequestListener<TranscodeType> targetListener,
      BaseRequestOptions<?> requestOptions,
      Executor callbackExecutor) {
    return buildRequestRecursive(
        target,
        targetListener,
        /*parentCoordinator=*/ null,
        transitionOptions,
        requestOptions.getPriority(),
        requestOptions.getOverrideWidth(),
        requestOptions.getOverrideHeight(),
        requestOptions,
        callbackExecutor);
  }

  private Request obtainRequest(
      Target<TranscodeType> target,
      RequestListener<TranscodeType> targetListener,
      BaseRequestOptions<?> requestOptions,
      RequestCoordinator requestCoordinator,
      TransitionOptions<?, ? super TranscodeType> transitionOptions,

同学们最后我们发现是SingleRequest.obtain来为我们构建的 Request 请求对象,开始只是初始化一些配置属性,下面我们就来找begin 开始的地方, 先来看下

track

 //这里对当前 class 加了一个同步锁避免线程引起的安全性  
 synchronized void track(@NonNull Target<?> target, @NonNull Request request) {
    //添加一个目标任务  
    targetTracker.track(target);
    //执行 Glide request
    requestTracker.runRequest(request);
  }
  public void runRequest(@NonNull Request request) {
    //添加一个请求
    requests.add(request);
    //是否暂停
    if (!isPaused) {
      //没有暂停,开始调用 Request begin 执行
      request.begin();
    } else {
      //如果调用了 暂停,清理请求
      request.clear();
      pendingRequests.add(request);
    }
  }

上面的逻辑是先为requests添加一个请求,看看是否是停止状态,如果不是就调用request.begin()执行。

这里的Request是一个接口,通过之前我们讲到buildRequest函数可知

Request的实现类是SingleRequest我们就直接看它的begin函数

  @Override
  public synchronized void begin() {
    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;
    //这里表示大小已经准备好了
    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));
    }
  }
  public synchronized void onSizeReady(int width, int height) {
    stateVerifier.throwIfRecycled();
    ....//都是一些初始化状态,配置属性,我们不用管。
 
    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);
  }

load

  public synchronized <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) {

    //拿到缓存或者请求的 key
    EngineKey key = keyFactory.buildKey(model, signature, width, height, transformations,
        resourceClass, transcodeClass, options);
        //根据 key 拿到活动缓存中的资源
    EngineResource<?> active = loadFromActiveResources(key, isMemoryCacheable);
    //如果 ActiveResources 活动缓存中有就回调出去
    if (active != null) {
      cb.onResourceReady(active, DataSource.MEMORY_CACHE);
      return null;
    }

    //尝试从 LruResourceCache 中找寻这个资源 
    EngineResource<?> cached = loadFromCache(key, isMemoryCacheable);
    if (cached != null) {
      //如果内存缓存 Lru 中资源存在回调出去
      cb.onResourceReady(cached, DataSource.MEMORY_CACHE);
      return null;
    }

    //------------- 走到这里说明活动缓存 跟内存 缓存都没有找到 ----------
-
    
    //根据 Key 看看缓存中是否正在执行
    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);
    }

    // --------------   走到这里说明是一个新的任务  ---------------
    // --------------   构建新的请求任务  ---------------
    EngineJob<R> engineJob =
        engineJobFactory.build(
            key,
            isMemoryCacheable,
            useUnlimitedSourceExecutorPool,
            useAnimationPool,
            onlyRetrieveFromCache);

    DecodeJob<R> decodeJob =
        decodeJobFactory.build(
            glideContext,
            model,
            key,
            signature,
            width,
            height,
            resourceClass,
            transcodeClass,
            priority,
            diskCacheStrategy,
            transformations,
            isTransformationRequired,
            isScaleOnlyOrNoTransform,
            onlyRetrieveFromCache,
            options,
            engineJob);
        //把当前需要执行的 key 添加进缓存
    jobs.put(key, engineJob);
        //执行任务的回调
    engineJob.addCallback(cb, callbackExecutor);
    //开始执行。
    engineJob.start(decodeJob);

    return new LoadStatus(cb, engineJob);
  }

通过engine.load 这个函数里面的逻辑,同学们我们可以总结3点:

1. 先构建请求或者缓存 KEY ;

2. 根据 KEY 从内存缓存中查找对应的资源数据(ActiveResources(活动缓存,内部 是一个 Map 用弱引用持有),LruResourceCache),如果有就回调 对应监听的 onResourceReady 表示数据准备好了。

3. 从执行缓存中查找对应 key 的任务

1. 如果找到了,就说明已经正在执行了,不用重复执行。

2. 没有找到,通过 EngineJob.start 开启一个新的请求任务执行。  

同学们下面我们就来看下engineJob.start 具体执行逻辑:

  public synchronized void start(DecodeJob<R> decodeJob) {
    this.decodeJob = decodeJob;
    //拿到 Glide 执行的线程池
    GlideExecutor executor = decodeJob.willDecodeFromCache()
        ? diskCacheExecutor
        : getActiveSourceExecutor();
    //开始执行
    executor.execute(decodeJob);
  }

通过DecodeJob源码得知,它是实现的Runnable接口,这里 GlideExecutor 线程池开始执行,就会启动 DecodeJob 的 run 函数,我们跟踪 run 的实现:

class DecodeJob<R> implements 
DataFetcherGenerator.FetcherReadyCallback,
    Runnable,
    Comparable<DecodeJob<?>>,
    Poolable {
      
      // 线程执行调用 run
      @Override
      public void run() {

        GlideTrace.beginSectionFormat("DecodeJob#run(model=%s)", model);

        DataFetcher<?> localFetcher = currentFetcher;
        try {
          //是否取消了当前请求
          if (isCancelled) {
            notifyFailed();
            return;
          }
          //执行
          runWrapped();
        } catch (CallbackException e) {

         . ....//一些错误回调
      }
    }

分析runWrapped:

  private void runWrapped() {
    switch (runReason) {
      case INITIALIZE:
        //获取资源状态
        stage = getNextStage(Stage.INITIALIZE);
        //根据当前资源状态,获取资源执行器
        currentGenerator = getNextGenerator();
        //执行
        runGenerators();
        break;
      ...
    }
}
  private Stage getNextStage(Stage current) {
    switch (current) {
      case INITIALIZE:
        //如果外部调用配置了资源缓存策略,那么返回 Stage.RESOURCE_CACHE
        //否则继续调用 Stage.RESOURCE_CACHE 执行。
        return diskCacheStrategy.decodeCachedResource()
            ? Stage.RESOURCE_CACHE : getNextStage(Stage.RESOURCE_CACHE);
      case RESOURCE_CACHE:
        //如果外部配置了源数据缓存,那么返回 Stage.DATA_CACHE
        //否则继续调用 getNextStage(Stage.DATA_CACHE)
        return diskCacheStrategy.decodeCachedData()
            ? Stage.DATA_CACHE : getNextStage(Stage.DATA_CACHE);
      case DATA_CACHE:
        //如果只能从缓存中获取数据,则直接返回 FINISHED,否则,返回SOURCE。
        //意思就是一个新的资源
        return onlyRetrieveFromCache ? Stage.FINISHED : Stage.SOURCE;
      case SOURCE:
      case FINISHED:
        return Stage.FINISHED;
      default:
        throw new IllegalArgumentException("Unrecognized stage: " + current);
    }
  }

通过上面代码可以知道,我们在找资源的执行器,这里由于我们没有在外部配置缓存 策略所以,直接从源数据加载,看下面代码:

  private DataFetcherGenerator getNextGenerator() {
    switch (stage) {
      //从资源缓存执行器
      case RESOURCE_CACHE:
        return new ResourceCacheGenerator(decodeHelper, this);
      //源数据磁盘缓存执行器
      case DATA_CACHE:
        return new DataCacheGenerator(decodeHelper, this);
      //什么都没有配置,源数据的执行器
      case SOURCE:
        return new SourceGenerator(decodeHelper, this);
      case FINISHED:
        return null;
      default:
        throw new IllegalStateException("Unrecognized stage: " + stage);
    }
  }

,由于我们什么都没有配置,返回的是SourceGenerator源数据执行器。继续下面代码执行:

  private void runGenerators() {
    currentThread = Thread.currentThread();
    startFetchTime = LogTime.getLogTime();
    boolean isStarted = false;
    //判断是否取消,是否开始
    //调用 DataFetcherGenerator.startNext() 判断是否是属于开始执行的任 务
    while (!isCancelled && currentGenerator != null
        && !(isStarted = currentGenerator.startNext())) {
   
      ....
  }

上面代码先看currentGenerator.startNext() 这句代码, DataFetcherGenerator 是一个抽象类,那么这里执行的实现类是哪一个,可以参考下面说明:

Stage.RESOURCE_CACHE【状态标记】 ---- 从磁盘中获取缓存的资源数据【作用】 --- ResourceCacheGenerator【执行器】

Stage.DATA_CACHE【状态标记】 ---- 从磁盘中获取缓存的源数据【作用】 ---DataCacheGenerator【执行器】

Stage.SOURCE【状态标记】 --- 一次新的请求任务 --- SourceGenerator【执行器】

因为这里我们没有配置缓存,那么直接看SourceGenerator

  @Override
  public boolean startNext() {
        ...
    loadData = null;
    boolean started = false;
    while (!started && hasNextModelLoader()) {
      //获取一个 ModelLoad 加载器
      loadData = helper.getLoadData().get(loadDataListIndex++);
      if (loadData != null
          && 
(helper.getDiskCacheStrategy().isDataCacheable(loadData.fetcher.g etDataSource())
          || helper.hasLoadPath(loadData.fetcher.getDataClass()))) {
        started = true;
        //使用加载器中的 fetcher 根据优先级加载数据
        loadData.fetcher.loadData(helper.getPriority(), this);
      }
    }
    return started;
  }

获取的是一个什么样的加载器,我们可以先 猜一下,因为没有配置任何缓存,所以可以猜得到是 http 请求了,那么是不是猜测 的那样的,我们一起来验证下。

  List<LoadData<?>> getLoadData() {
    if (!isLoadDataSet) {
      isLoadDataSet = true;
      loadData.clear(); 
      //从 Glide 注册的 Model 来获取加载器(注册是在 Glide 初始化的时候通
过 registry
       // .append()添加的)
      List<ModelLoader<Object, ?>> modelLoaders = glideContext.getRegistry().getModelLoaders(model);
     
      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;
  }

首先拿到一个加载器的容器,加载器是在 Glide 初始化的时候 通过Registry.append()添加的,这里因为同学们我们以网络链接举例的。所以, ModelLoad 的实现类是HttpGlideUrlLoader加载器,我们看下它的具体实现:

  @Override
  public LoadData<InputStream> buildLoadData(@NonNull GlideUrl model, int width, int height,
      @NonNull Options options) {
    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);
    // 【同学们注意:之前有开发者看了一周Glide源码,也找不到网络请求的地方,我 们现在就已经找到了,很伟大了,可以给自己鼓掌】 
    return new LoadData<>(url, new HttpUrlFetcher(url, timeout));
  }

这里看到是返回的一个HttpUrlFetcher 给加载器。加载器我们拿到了,现在开始 加载,返回到刚刚的源码,请看下面:

class DataCacheGenerator implements DataFetcherGenerator,
    DataFetcher.DataCallback<Object> {
      
      //挑重要代码
       @Override
  public boolean startNext() {
 ....
    while (!started && hasNextModelLoader()) {
      ModelLoader<File, ?> modelLoader = modelLoaders.get(modelLoaderIndex++);
      loadData =
          modelLoader.buildLoadData(cacheFile, helper.getWidth(), helper.getHeight(),
              helper.getOptions());
      if (loadData != null && helper.hasLoadPath(loadData.fetcher.getDataClass())) {
        started = true;
        //通过拿到的加载器,开始加载数据
        loadData.fetcher.loadData(helper.getPriority(), this);
      }
    }
    return started;
  }   
}

因为刚刚同学们知道了这里拿到的加载器是HttpUrlFetcher 所以我们直接看它的loadData 实现:

  @Override
  public void loadData(@NonNull Priority priority,
      @NonNull DataCallback<? super InputStream> callback) {
    long startTime = LogTime.getLogTime();
    try {
      //http 请求,返回一个 InputStream 输入流
      InputStream result = loadDataWithRedirects(glideUrl.toURL(), 0, null, glideUrl.getHeaders());
      //将 InputStream 以回调形式回调出去
      callback.onDataReady(result);
    } catch (IOException e) {
      callback.onLoadFailed(e);
    } finally {
     ...
    }
  }

继续看loadDataWithRedirects 这个函数是怎么生成的一个 InputStream :

  private InputStream loadDataWithRedirects(URL url, int redirects, URL lastUrl,
      Map<String, String> headers) throws IOException {
    if (redirects >= MAXIMUM_REDIRECTS) {
      throw new HttpException("Too many (> " + MAXIMUM_REDIRECTS + ") redirects!");
    } else {

      try {
        if (lastUrl != null && url.toURI().equals(lastUrl.toURI())) {
          throw new HttpException("In re-direct loop");
        }
      } catch (URISyntaxException e) {
        // Do nothing, this is best effort.
      }
    }

    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);

    urlConnection.setInstanceFollowRedirects(false);
    urlConnection.connect();

    stream = urlConnection.getInputStream();
    if (isCancelled) {
      return null;
    }
    final int statusCode = urlConnection.getResponseCode();
    if (isHttpOk(statusCode)) {
      return getStreamForSuccessfulRequest(urlConnection);
    } 
    ...//抛的异常我们暂时先不管
  }

已经到了同学们熟悉的 Http 请求了,这里是 HttpURLConnection 作为 Glide 底层 成网络请求的。请求成功之后直接返回的是一个输入流,最后会通过onDataReady回调到 DecodeJob onDataFetcherReady 函数中。跟下回调,回调到 SourceGenerator :

  @Override
  public void onDataReady(Object data) {
    DiskCacheStrategy diskCacheStrategy = helper.getDiskCacheStrategy();
    if (data != null && diskCacheStrategy.isDataCacheable(loadData.fetcher.getDataSource( ))) {
      dataToCache = data;
      cb.reschedule();
    } else {
      cb.onDataFetcherReady(loadData.sourceKey, data, loadData.fetcher,
          loadData.fetcher.getDataSource(), originalKey);
    }
  }

这里会有 else 因为我们没有配置缓存,继续回调:

 

class DecodeJob<R> implements 
DataFetcherGenerator.FetcherReadyCallback,
    Runnable,
    Comparable<DecodeJob<?>>,
    Poolable {
      ...
      @Override
      public void onDataFetcherReady(Key sourceKey, Object data, DataFetcher<?> fetcher,
          DataSource dataSource, Key attemptedKey) {
        this.currentSourceKey = sourceKey; //当前返回数据的 key
        this.currentData = data; //返回的数据
        this.currentFetcher = fetcher; //返回的数据执行器,这里可以理解
为 HttpUrlFetcher
        this.currentDataSource = dataSource; //数据来源 url
        this.currentAttemptingKey = attemptedKey;
        if (Thread.currentThread() != currentThread) {
          runReason = RunReason.DECODE_DATA;
          callback.reschedule(this);
        } else {
         
 GlideTrace.beginSection("DecodeJob.decodeFromRetrievedData");
          try {
            //解析返回回来的数据
            decodeFromRetrievedData();
          } finally {
            GlideTrace.endSection();
          }
        }
      }   
      ...
    }

  //解析返回的数据
  private void decodeFromRetrievedData() {
    Resource<R> resource = null;
    try {
      // 调用 decodeFrom 解析 数据;HttpUrlFetcher , InputStream ,  currentDataSource
      resource = decodeFromData(currentFetcher, currentData, currentDataSource);
    } catch (GlideException e) {
      e.setLoggingDetails(currentAttemptingKey, currentDataSource);
      throwables.add(e);
    }
    //解析完成后,通知下去
    if (resource != null) {
      notifyEncodeAndRelease(resource, currentDataSource);
    } else {
      runGenerators();
    }
  }

同学们继续跟 decodeFromData 看看怎么解析成 Resource 的:

  private <Data> Resource<R> decodeFromData(DataFetcher<?> fetcher, Data data,
      DataSource dataSource) throws GlideException {
      ...  
      Resource<R> result = decodeFromFetcher(data, dataSource);
      ....
      return result;
    } finally {
      fetcher.cleanup();
    }
  }

  @SuppressWarnings("unchecked")
  private <Data> Resource<R> decodeFromFetcher(Data data, DataSource dataSource)
      throws GlideException {
    //获取当前数据类的解析器 LoadPath 
    LoadPath<Data, ?, R> path = decodeHelper.getLoadPath((Class<Data>) data.getClass());
    //通过 LoadPath 解析器来解析数据
    return runLoadPath(data, dataSource, path);
  }
  private <Data, ResourceType> Resource<R> runLoadPath(Data data, DataSource dataSource,
      LoadPath<Data, ResourceType, R> path) throws GlideException {
    Options options = getOptionsWithHardwareConfig(dataSource);
    
    //因为这里返回的是一个 InputStream 所以 这里拿到的是 InputStreamRewinder
    DataRewinder<Data> rewinder = glideContext.getRegistry().getRewinder(data);
    try {
      //将解析资源的任务转移到 Load.path 方法中
      return path.load(
          rewinder, options, width, height, new 
DecodeCallback<ResourceType>(dataSource));
    } finally {
      rewinder.cleanup();
    }
  }

注意上面代码,为了解析数据首先构建一个 LoadPath, 然后创建一个 InputStreamRewinder 类型的 DataRewinder, 最终将数据解析的操作放到了 LoadPath.load 方法中 ,接下来看下 LoadPath.load 方法的具体逻辑操作:

  public Resource<Transcode> load(DataRewinder<Data> rewinder, @NonNull Options options, int width,
      int height, DecodePath.DecodeCallback<ResourceType> decodeCallback) throws GlideException {
      
    try {
      return loadWithExceptionList(rewinder, options, width, height, decodeCallback, throwables);
    } finally {
      listPool.release(throwables);
    }
  }
  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;
   
    //遍历内部存储的 DecodePath 集合,通过他们来解析数据
    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) {
       ...
      }
     ...
    return result;
  }

看path.decode

  public Resource<Transcode> decode(DataRewinder<DataType> rewinder, int width, int height,
      @NonNull Options options, DecodeCallback<ResourceType> callback) throws GlideException {
    //调用 decodeResourec 将数据解析成中间资源
    Resource<ResourceType> decoded = decodeResource(rewinder, width, height, options);
    //解析完数据回调出去
    Resource<ResourceType> transformed = callback.onResourceDecoded(decoded);
    //转换资源为目标资源
    return transcoder.transcode(transformed, options);
  }

看看 decodeResource 怎么解析成中间资源的:

  @NonNull
  private Resource<ResourceType> decodeResource(DataRewinder<DataType> rewinder, int width,
      int height, @NonNull Options options) throws GlideException {
   ...
    try {
      return decodeResourceWithList(rewinder, width, height, options, exceptions);
    } finally {
    ...
    }
  }

  @NonNull
  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();
          // 调用 ResourceDecoder.decode 解析数据
          result = decoder.decode(data, width, height, options);
        }

      } catch (IOException | RuntimeException | OutOfMemoryError e) {
                ...
      }
    return result;
  }

可以看到数据解析的任务最终是通过 DecodePath 来执行的, 它内部有三大步 操作

第一大步:deResource 将源数据解析成资源(源数据: InputStream, 中间产物: Bitmap)

第二大步:调用 DecodeCallback.onResourceDecoded 处理资源

第三大步:调用 ResourceTranscoder.transcode 将资源转为目标资源(目标资源类型: Drawable)

可以发现,通过上面的 decoder.decode 源码可知,它是一个接口,由于我们 这里的源数据是 InputStream,所以,它的实现类是 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;

    ....
      
    try {
      // 根据请求配置来对数据进行采样压缩,获取一个 Resource<Bitmap> 
      return downsampler.decode(invalidatingStream, width, height, options, callbacks);
    } finally {
      ....
    }
  }

 

注意:具体怎么采样压缩,先不用关注具体实现(先不关心支线,只管 主线),现在拿到了一个 Bitmap 数据,我们需要通过回调出去,请看下面代码:

  public Resource<Transcode> decode(DataRewinder<DataType> rewinder, int width, int height,
      @NonNull Options options, DecodeCallback<ResourceType> callback) throws GlideException {
    //第一步: 调用 decodeResourec 将数据解析成中间资源 Bitmap
    Resource<ResourceType> decoded = decodeResource(rewinder, width, height, options);
    //第二步: 解析完数据回调出去
    Resource<ResourceType> transformed = callback.onResourceDecoded(decoded);
    //第三步: 转换资源为目标资源 Bitmap to Drawable
    return transcoder.transcode(transformed, options);
  }

最后会回调到 DecodeJob

class DecodeJob<R> implements 
DataFetcherGenerator.FetcherReadyCallback,
    Runnable,
    Comparable<DecodeJob<?>>,
    Poolable {
      ...  
    @Override
    public Resource<Z> onResourceDecoded(@NonNull Resource<Z> decoded) {
      return DecodeJob.this.onResourceDecoded(dataSource, decoded);
    } 
      ... 
}

同学们可以看到 onResourceDecoded 中, 主要是对中间资源做了如下的操作:

第一步:对资源进行了转换操作。比如 Fit_Center,CenterCrop, 这些都是在请求的 时候配置的

第二步:构建磁盘缓存的 key

注意:最终就是将 Bitmap 转换成 Drawable 了操作了 ,请看下面代码

public class DecodePath<DataType, ResourceType, Transcode> { 
  省略成吨的代码 ...  
  Resource<Transcode> decode(DataRewinder<DataType> rewinder, int width, int height,
      @NonNull Options options, DecodeCallback<ResourceType> callback) throws GlideException {
    //第一步: 调用 decodeResourec 将数据解析成中间资源 Bitmap
    Resource<ResourceType> decoded = decodeResource(rewinder, width, height, options);
    //第二步: 解析完数据回调出去
    Resource<ResourceType> transformed = callback.onResourceDecoded(decoded);
    //第三步: 转换资源为目标资源 Bitmap to Drawable
    return transcoder.transcode(transformed, options);
  }
  省略成吨的代码 ... 
}

只看第三步,通过源码可知,ResourceTranscoder 是一个接口,又因为解析 完的数据是 Bitmap 所以它的实现类是 BitmapDrawableTranscoder ,最后看下它的 transcode 具体实现:

public class BitmapDrawableTranscoder implements ResourceTranscoder<Bitmap, BitmapDrawable> {
  @Nullable
  @Override
  public Resource<BitmapDrawable> transcode(@NonNull Resource<Bitmap> toTranscode,
      @NonNull Options options) {
    return LazyBitmapDrawableResource.obtain(resources, toTranscode);
  } 
}
public final class LazyBitmapDrawableResource implements Resource<BitmapDrawable>,
    Initializable {

  private final Resources resources;
  private final Resource<Bitmap> bitmapResource;

  @Deprecated
  public static LazyBitmapDrawableResource obtain(Context context, Bitmap bitmap) {
    return
        (LazyBitmapDrawableResource)
            obtain(
                context.getResources(),
                BitmapResource.obtain(bitmap, Glide.get(context).getBitmapPool()));
  }

  @Deprecated
  public static LazyBitmapDrawableResource obtain(Resources resources, BitmapPool bitmapPool,
      Bitmap bitmap) {
    return
        (LazyBitmapDrawableResource) obtain(resources, BitmapResource.obtain(bitmap, bitmapPool));
  }

  @Nullable
  public static Resource<BitmapDrawable> obtain(
      @NonNull Resources resources, @Nullable Resource<Bitmap> bitmapResource) {
    if (bitmapResource == null) {
      return null;
    }
    return new LazyBitmapDrawableResource(resources, bitmapResource);
  }
  private LazyBitmapDrawableResource(@NonNull Resources resources,
      @NonNull Resource<Bitmap> bitmapResource) {
    this.resources = Preconditions.checkNotNull(resources);
    this.bitmapResource = 
Preconditions.checkNotNull(bitmapResource);
  }

  @NonNull
  @Override
  public Class<BitmapDrawable> getResourceClass() {
    return BitmapDrawable.class;
  }

  // Get 方法反回了一个 BitmapDrawable 对象
  @NonNull
  @Override
  public BitmapDrawable get() {
    return new BitmapDrawable(resources, bitmapResource.get());
  }

  @Override
  public int getSize() {
    return bitmapResource.getSize();
  }

  @Override
  public void recycle() {
    bitmapResource.recycle();
  }

  @Override
  public void initialize() {
    if (bitmapResource instanceof Initializable) {
      ((Initializable) bitmapResource).initialize();
    }
  }
}

转化终于完成了 ,将我们解析到的 bitmap 存放到LazyBitmapDrawableResource 内部, 然后外界通过 get 方法就可以获取到一个 BitmapDrawable 的对象了,解析完就到了展示数据了,请看下面代码:

class DecodeJob<R> implements 
DataFetcherGenerator.FetcherReadyCallback,
    Runnable,
    Comparable<DecodeJob<?>>,
    Poolable {

  //解析返回的数据
  private void decodeFromRetrievedData() {
    Resource<R> resource = null;
    try {
      //第一步: 调用 decodeFrom 解析 数据;HttpUrlFetcher , InputStream ,  currentDataSource
      resource = decodeFromData(currentFetcher, currentData, currentDataSource);
    } catch (GlideException e) {
      e.setLoggingDetails(currentAttemptingKey, currentDataSource);
      throwables.add(e);
    }
    //第二步: 解析完成后,通知下去
    if (resource != null) {
      notifyEncodeAndRelease(resource, currentDataSource);
    } else {
      runGenerators();
    }  
 }

第一步就解析完了数据, 现在第二步执行 notifyEncodeAndRelease函数:

private void notifyEncodeAndRelease(Resource<R> resource, DataSource dataSource) {
    ...
    //通知调用层数据已经装备好了
    notifyComplete(result, dataSource);

    stage = Stage.ENCODE;
    try {
      //这里就是将资源磁盘缓存
      if (deferredEncodeManager.hasResourceToEncode()) {
        deferredEncodeManager.encode(diskCacheProvider, options);
      }
    } finally {
     ...
    }
    //完成
    onEncodeComplete();
  }

  private void notifyComplete(Resource<R> resource, DataSource dataSource) {
    setNotifiedOrThrow();
    // 在 DecodeJob 的构建中, 我们知道这个 Callback 是 EngineJob
    callback.onResourceReady(resource, dataSource);
  }
}

可以看到上面的 DecodeJob.decodeFromRetrievedData 中主要做了三个 处理:

第一个处理:解析返回回来的资源。

第二个处理:拿到解析的资源,如果配置了本地缓存,就缓存到磁盘。

第三个处理:通知上层资源准备就绪,可以使用了。

我们直接看 EngineJob 的 onResourceReady 回调函数:

  @Override
  public void onResourceReady(Resource<R> resource, DataSource dataSource) {
    synchronized (this) {
      this.resource = resource;
      this.dataSource = dataSource;
    }
    notifyCallbacksOfResult();
  }

  @Synthetic
  void notifyCallbacksOfResult() {
    ResourceCallbacksAndExecutors copy;
    Key localKey;
    EngineResource<?> localResource;
    synchronized (this) {
      stateVerifier.throwIfRecycled();
      if (isCancelled) {
        resource.recycle();
        release();
        return;
      } else if (cbs.isEmpty()) {
      ... 
      }
      engineResource = engineResourceFactory.build(resource, isCacheable);
      hasResource = true;
      copy = cbs.copy();
      incrementPendingCallbacks(copy.size() + 1);

      localKey = key;
      localResource = engineResource;
    }

    //回调上层 Engine 任务完成了
    listener.onEngineJobComplete(this, localKey, localResource);

    //遍历资源回调给 ImageViewTarget 
    for (final ResourceCallbackAndExecutor entry : copy) {
      entry.executor.execute(new CallResourceReady(entry.cb));
    }
    decrementPendingCallbacks();
  }

通过上面 EngineJob 的 onResourceReady 回调函数 主要做了 两个处理:

第一个处理:通知上层任务完成。

第二个处理:回调 ImageViewTarget 用于展示数据。

看下 listener.onEngineJobComplete 具体实现:

  @SuppressWarnings("unchecked")
  @Override
  public synchronized void onEngineJobComplete(
      EngineJob<?> engineJob, Key key, EngineResource<?> resource) {
    if (resource != null) {
      resource.setResourceListener(key, this);
            //收到下游返回回来的资源,添加到活动缓存中
      if (resource.isCacheable()) {
        activeResources.activate(key, resource);
      }
    }
    jobs.removeIfCurrent(key, engineJob);
  }

最终通知 ImageViewTarget ,

    //遍历资源回调给 ImageViewTarget 
    for (final ResourceCallbackAndExecutor entry : copy) {
      entry.executor.execute(new CallResourceReady(entry.cb));
    }
  private class CallResourceReady implements Runnable {

    private final ResourceCallback cb;

    CallResourceReady(ResourceCallback cb) {
      this.cb = cb;
    }

    @Override
    public void run() {
      synchronized (EngineJob.this) {
        if (cbs.contains(cb)) {
         ...
          //返回准备好的资源
          callCallbackOnResourceReady(cb);
          removeCallback(cb);
        }
        decrementPendingCallbacks();
      }
    }
  }

看到 CallResourceReady 实现 Runnable ,当 entry.executor.execute 线程池执行的时候就会调用 run ,最后我们继续跟 callCallbackOnResourceReady 函数:

  @Synthetic
  synchronized void callCallbackOnResourceReady(ResourceCallback cb) {
    try {
      //回调给 SingleRequest
      cb.onResourceReady(engineResource, dataSource);
    } catch (Throwable t) {
      throw new CallbackException(t);
    }
  }
 public synchronized void onResourceReady(Resource<?> resource, DataSource dataSource) {
    stateVerifier.throwIfRecycled();
    loadStatus = null;
    ... 省略成吨的代码
    Object received = resource.get();
    if (received == null || 
!transcodeClass.isAssignableFrom(received.getClass())) {
      releaseResource(resource);
      ... 省略成吨的代码
      onLoadFailed(exception);
      return;
    }

    if (!canSetResource()) {
      releaseResource(resource);
      status = Status.COMPLETE;
      return;
    }

   //当资源准备好的时候
    onResourceReady((Resource<R>) resource, (R) received, dataSource);
  }


private synchronized void onResourceReady(Resource<R> resource, R result, DataSource dataSource) {
      ... 省略成吨的代码
      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();
  }

这一步主要把准备好的资源回调给显示层,看下面代码

public abstract class ImageViewTarget<Z> extends ViewTarget<ImageView, Z>
    implements Transition.ViewAdapter { 
  ...
  @Override
  public void onResourceReady(@NonNull Z resource, @Nullable Transition<? super Z> transition) {
    if (transition == null || !transition.transition(resource, this)) {
      setResourceInternal(resource);
    } else {
      maybeUpdateAnimatable(resource);
    }
  }
 
  protected abstract void setResource(@Nullable Z resource);
  ...
}

  private void setResourceInternal(@Nullable Z resource) {
    //调用 setResource 函数,将资源显示出来
    setResource(resource);
    ...
}

在最开始构建的时候,我们知道只有调用 asBitmap 的时候实现类 是BitmapImageViewTarget ,在这里的测试,并没有调用这个函数,所以它的实现 类是DrawableImageViewTarget,具体看下它内部实现:

public class DrawableImageViewTarget extends ImageViewTarget<Drawable> {

  public DrawableImageViewTarget(ImageView view) {
    super(view);
  }

  // Public API.
  @SuppressWarnings({"unused", "deprecation"})
  @Deprecated
  public DrawableImageViewTarget(ImageView view, boolean waitForLayout) {
    super(view, waitForLayout);
  }

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

这里看到抽象类中调用了 setResource ,子 类实现并调用了 view.setImageDrawable(resource); 图片现在算是真正的显示出 来了。 我们就看到了图片的显示:

生命周期的意义:

就是 Glide框架内部 会搞一个空白的Fragment 关联到 用户的 Activity或者 Fragment,当用户的Activity或者Fragment 发生Stop Start 的时候,空白的 Fragment就监听到了,从而根据用户Activity或者Fragment的变化,从而做出自 己框架的处理

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值