Glide源码分析之生命周期绑定(一)

Glide源码分析之生命周期绑定(一)

一、几大主流图片加载框架对比

1、Glide

  • 1、多种图片格式的缓存,适用于更多的内容表现形式(如Gif、WebP、缩略图、Video)
  • 2、生命周期集成(根据Activity或者Fragment的生命周期管理图片加载请求)
  • 3、高效处理Bitmap(bitmap的复用和主动回收,减少系统回收压力)
  • 4、高效的缓存策略,灵活(Picasso只会缓存原始尺寸的图片,Glide缓存的是多种规格),加载速度快且内存开销小(默认Bitmap格式的不同,使得内存开销是Picasso的一半)

2、Fresco

  • 最大的优势在于5.0以下(最低2.3)的bitmap加载。在5.0以下系统,Fresco将图片放到一个特别的内存区域(Ashmem区)
  • 大大减少OOM(在更底层的Native层对OOM进行处理,图片将不再占用App的内存)
  • 适用于需要高性能加载大量图片的场景

二、Glide介绍

1、简述

Glide是一个性能优良,受欢迎的第三方图片加载框架,在节省内存和加载流畅方面有了体现和优化。内部核心机制主要体现如下几点:

  • 1、与调用环境生命周期: RequestManagerFragment & SupportRequestManagerFragment

  • 2、内存的三级缓存池:

    class ActiveResources {//缓存当前正在使用的资源(注意是弱引用)
     //...
    }
     class LruResourceCache {//缓存最近使用过但是当前未使用的资源,LRU算法
     //...
    }
    class BitmapPool {//缓存所有被释放的图片,内存复用,LRU算法
     //...
    }
  • 3、内存复用机制: BitmapPool

2、框架架构图

3、逻辑分块图

4、加载一张图片流程图

三、基本使用

使用Glide加载图片的方式很简单,就是builder链式调用的方式使用。

Glide.with(context).load(url).into(iv);

四、包结构

五、核心类源码解析

1、Glide创建RequestManagerRetriever过程

Glide类是一个单例类, 通过Glide#get(Context)方法获取实例,Glide是一个全局配置类,可配置Engine、MemeoryCache、BitmapPool、Encoder、Decoder等,此外可以由Glide#with(Context)来创建RequestManager对象。

Glide构造器:

  @SuppressWarnings("PMD.UnusedFormalParameter")
  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;
    this.bitmapPool = bitmapPool;
    this.arrayPool = arrayPool;
    this.memoryCache = memoryCache;
    this.requestManagerRetriever = requestManagerRetriever;
    this.connectivityMonitorFactory = connectivityMonitorFactory;
    this.defaultRequestOptionsFactory = defaultRequestOptionsFactory;
    //...
  }

Glide通过Glide#with(Context)来创建RequestManager, Glide中有6个with重载方法。

 //通过传入Context来构建一个RequestManager 
 public static RequestManager with(@NonNull Context context){
     return getRetriever(context).get(context);
 }
 //通过传入Activity来构建一个RequestManager
 public static RequestManager with(@NonNull Activity activity){
     return getRetriever(activity).get(activity);
 }
 //通过传入FragmentActivity来构建一个RequestManager
 public static RequestManager with(@NonNull FragmentActivity activity){
     return getRetriever(activity).get(activity);
 }
 //通过传入Fragment来构建一个RequestManager
  public static RequestManager with(@NonNull Fragment fragment){
      return getRetriever(fragment.getContext()).get(fragment);
  }
  //通过传入android.app.Fragment来构建一个RequestManager
  public static RequestManager with(@NonNull android.app.Fragment fragment){
      return getRetriever(fragment.getActivity()).get(fragment);
  }
  //通过传入View来构建一个RequestManager
  public static RequestManager with(@NonNull View view){
      return getRetriever(view.getContext()).get(view);
  }

通过上述with方法看出,RequestManager创建是通过委托给RequestManagerRetriever来创建的,RequestManagerRetriever也是一个单例类,那么一起来看下getRetriever的实现。

  @NonNull
  private static RequestManagerRetriever getRetriever(@Nullable Context context) {

    return Glide.get(context).getRequestManagerRetriever();//先通过Glide.get(context)获取Glide单例实例,然后再通过Glide实例的getRequestManagerRetriever获取RequestManagerRetriever实例
  }

通过上述的getRetriever方法实现可以看出,先通过Glide.get(context)获取Glide单例实例,然后再通过Glide实例的getRequestManagerRetriever获取RequestManagerRetriever实例,一起来看下Glide.get(context)获取Glide实例对象。

  @NonNull
  public static Glide get(@NonNull Context context) {
  //如果glide实例为null
    if (glide == null) {
     //生成一个AppGlideModule
      GeneratedAppGlideModule annotationGeneratedModule =
        getAnnotationGeneratedGlideModules(context.getApplicationContext());
      synchronized (Glide.class) {
        if (glide == null) {
          //检查并初始化Glide
          checkAndInitializeGlide(context, annotationGeneratedModule);
        }
      }
    }
    return glide;
  }

接着查看Glide#checkAndInitializeGlide的实现

 private static void checkAndInitializeGlide(
      @NonNull Context context, @Nullable GeneratedAppGlideModule generatedAppGlideModule) {
    //不能在正在运行线程中initGlide()或者在多处地方调用Glide.get(context)
    if (isInitializing) {
      throw new IllegalStateException(
          "You cannot call Glide.get() in registerComponents(),"
              + " use the provided Glide instance instead");
    }
    isInitializing = true;
    //初始化Glide
    initializeGlide(context, generatedAppGlideModule);
    isInitializing = false;
  }

  //初始化Glide
   private static void initializeGlide(
      @NonNull Context context, @Nullable GeneratedAppGlideModule generatedAppGlideModule) {

    initializeGlide(context, new GlideBuilder(), generatedAppGlideModule);
  }

接着查看Glide#initializeGlide(Context, GlideBuilder)的实现

private static void initializeGlide(
      @NonNull Context context,
      @NonNull GlideBuilder builder,
      @Nullable GeneratedAppGlideModule annotationGeneratedModule) {
    Context applicationContext = context.getApplicationContext();
    ...
    //通过GlideBuilder创建一个Glide实例对象
    Glide glide = builder.build(applicationContext);
    ...
    applicationContext.registerComponentCallbacks(glide);
    //并且初始化Glide,静态实例glide
    Glide.glide = glide;
  }

接着查看GlideBuilder#build(Context)的实现

@NonNull
  Glide build(@NonNull Context context) {
    //指定默认的请求图片资源线程池(source)
    if (sourceExecutor == null) {
      sourceExecutor = GlideExecutor.newSourceExecutor();
    }
    //指定默认的本地缓存线程池(disk-cache)
    if (diskCacheExecutor == null) {
      diskCacheExecutor = GlideExecutor.newDiskCacheExecutor();
    }
    //指定默认的动画加载线程池(animation)
    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) {
     //依据设备的屏幕密度和尺寸设置各种BitmapPool的size大小
      int size = memorySizeCalculator.getBitmapPoolSize();
      if (size > 0) {//如果BitmapPool的size大于0,创建LruBitmapPool对象
        bitmapPool = new LruBitmapPool(size);
      } else {//否则创建BitmapPoolAdapter对象
        bitmapPool = new BitmapPoolAdapter();
      }
    }

    //创建数组池
    if (arrayPool == null) {
      arrayPool = new LruArrayPool(memorySizeCalculator.getArrayPoolSizeInBytes());
    }

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

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

    //创建Engine
    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);
    }
    //注意: 这里创建RequestManagerRetriever对象
    RequestManagerRetriever requestManagerRetriever =
        new RequestManagerRetriever(requestManagerFactory);
     //最后创建Glide对象实例,并返回
    return new Glide(
        context,
        engine,
        memoryCache,
        bitmapPool,
        arrayPool,
        requestManagerRetriever,
        connectivityMonitorFactory,
        logLevel,
        defaultRequestOptionsFactory,
        defaultTransitionOptions,
        defaultRequestListeners,
        isLoggingRequestOriginsEnabled,
        isImageDecoderEnabledForBitmaps);
  }

一起来看完了Glide.get(context)创建Glide实例对象,并且在创建过程中创建了RequestManagerRetriever 对象,一起看下RequestManagerRetriever创建过程

 public RequestManagerRetriever(@Nullable RequestManagerFactory factory) {
    this.factory = factory != null ? factory : DEFAULT_FACTORY;//如果外部没有指定RequestManagerFactory,就是使用默认的RequestManagerFactory DEFAULT_FACTORY
    handler = new Handler(Looper.getMainLooper(), this /* Callback */);//创建主循环中handler
  }

实际上RequestManager对象是通过RequestManagerFactory工厂对象的build函数创建的,一起来看下

  private static final RequestManagerFactory DEFAULT_FACTORY =
      new RequestManagerFactory() {
        @NonNull
        @Override
        //RequestManagerFactory的build方法,
        public RequestManager build(
            @NonNull Glide glide,
            @NonNull Lifecycle lifecycle,
            @NonNull RequestManagerTreeNode requestManagerTreeNode,
            @NonNull Context context) {
            //创建RequestManager对象,传入参数分别为glide实例、Lifecycle、RequestManagerTreeNode、Context
          return new RequestManager(glide, lifecycle, requestManagerTreeNode, context);
        }
      };

那么Glide.get(context).getRequestManagerRetriever(); 将会获得一个RequestManagerRetriever 对象。

@NonNull
  public RequestManagerRetriever getRequestManagerRetriever() {
    return requestManagerRetriever;
  }

调用流程图:

2、通过RequestManagerRetriever对象获取RequestManager对象过程(完成生命周期的绑定)

我们拿到了RequestManagerRetriever实例后,然后通过它的get方法获得RequestManager对象。一起来看下RequestManagerRetriever#get(Context)方法,上面重载的6个Glide.with方法拿到RequestManagerRetriever实例后,都会通过它对应的get方法来获得RequestManager对象。


 @NonNull
  public RequestManager get(@NonNull Context context) {
    if (context == null) {
      //context不允许为null
      throw new IllegalArgumentException("You cannot start a load on a null Context");
    } else if (Util.isOnMainThread() && !(context instanceof Application)) {//如果当前是主UI线程并且context不是Appllication
      if (context instanceof FragmentActivity) {
        //如果context是一个FragmentActivity,那么调用参数为FragmentActivity的get方法
        return get((FragmentActivity) context);
      } else if (context instanceof Activity) {
      //如果context是一个Activity,那么调用参数为Activity的get方法
        return get((Activity) context);
      } else if (context instanceof ContextWrapper
      //如果context是一个ContextWrapper并且baseContext不是Application Context,那么调用参数为Activity的get方法,递归调用当前的get方法,直到找到匹配的get方法
          && ((ContextWrapper) context).getBaseContext().getApplicationContext() != null) {
        return get(((ContextWrapper) context).getBaseContext());
      }
    }

    //最后找不到匹配的 FragmentActivity、Activity的get方法会创建一个与Application生命周期绑定的RequestManager对象
    return getApplicationManager(context);
  }

如果传入的contextApplication Context或者当前线程是非主线程会调用getApplicationManager得到RequestManager实例.

 @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) {
          //一般情况下paused、resume生命周期关注都是通过手动添加空白的Fragment到Fragment或Activity的生命周期来通知的。但是在当前case中,RequestManager与Application绑定将不会收到生命周期事件的回调,所以我们必须通过ApplicationLifecycle强制去开启恢复. 
          Glide glide = Glide.get(context.getApplicationContext());
          applicationManager =
              factory.build(
                  glide,
                  new ApplicationLifecycle(),
                  new EmptyRequestManagerTreeNode(),
                  context.getApplicationContext());
        }
      }
    }

    return applicationManager;
  } 

如果传入的context是非Application Context并且当前线程是主线程会调用以下几个get方法

  @NonNull
  //1、如果with方法传入参数类型是FragmentActivity的get方法获取RequestManager实例。
  public RequestManager get(@NonNull FragmentActivity activity) {
    //如果是非主线程,那么调用get(activity.getApplicationContext())最后调用getApplicationManager(context)来创建一个与ApplicationManager绑定的RequestManager实例。
    if (Util.isOnBackgroundThread()) {
      return get(activity.getApplicationContext());
    } else {
      assertNotDestroyed(activity);
      //如果是FragmentActivity,先获得FragmentManager
      FragmentManager fm = activity.getSupportFragmentManager();
      //最后调用supportFragmentGet方法返回RequestManager实例
      return supportFragmentGet(activity, fm, /*parentHint=*/ null, isActivityVisible(activity));
    }
  }

//2、如果with方法传入参数类型是Fragment的get方法获取RequestManager实例
@NonNull
  public RequestManager get(@NonNull Fragment fragment) {
    //如果是非主线程,那么调用get(activity.getApplicationContext())最后调用getApplicationManager(context)来创建一个与ApplicationManager绑定的RequestManager实例。 
    if (Util.isOnBackgroundThread()) {
      return get(fragment.getContext().getApplicationContext());
    } else {
      //如果是fragment,通过getChildFragmentManager获取FragmentManager
      FragmentManager fm = fragment.getChildFragmentManager();
      //最后调用supportFragmentGet方法返回RequestManager实例
      return supportFragmentGet(fragment.getContext(), fm, fragment, fragment.isVisible());
    }
  }

//3、如果with方法传入参数类型是Activity的get方法获取RequestManager实例
public RequestManager get(@NonNull Activity activity) {
//如果是非主线程,那么调用get(activity.getApplicationContext())最后调用getApplicationManager(context)来创建一个与ApplicationManager绑定的RequestManager实例。
 if (Util.isOnBackgroundThread()) {
   return get(activity.getApplicationContext());
 } else {
 assertNotDestroyed(activity);
 //如果是Activity,先获得android.app.FragmentManager
 android.app.FragmentManager fm = activity.getFragmentManager();
 //最后调用fragmentGet方法返回RequestManager实例
 return fragmentGet(activity, fm, /*parentHint=*/ null, isActivityVisible(activity));
   }
 }

//4、如果with方法传入参数类型是android.app.Fragment的get方法获取RequestManager实例
 public RequestManager get(@NonNull android.app.Fragment fragment) {
    //如果是非主线程或API小于API17,API17以下版本没有android.app.Fragment,那么调用get(activity.getApplicationContext())最后调用getApplicationManager(context)来创建一个与ApplicationManager绑定的RequestManager实例。
    if (Util.isOnBackgroundThread() || Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
      return get(fragment.getActivity().getApplicationContext());
    } else {
    //如果是android.app.fragment,通过getChildFragmentManager获取android.app.FragmentManager
      android.app.FragmentManager fm = fragment.getChildFragmentManager();
      //最后调用fragmentGet方法返回RequestManager实例
      return fragmentGet(fragment.getActivity(), fm, fragment, fragment.isVisible());
    }
  }

//5、如果with方法传入参数类型是View的get方法获取RequestManager实例
  public RequestManager get(@NonNull View view) {
    //如果是非主线程,那么调用get(activity.getApplicationContext())最后调用getApplicationManager(context)来创建一个与Application绑定的RequestManager实例。
    if (Util.isOnBackgroundThread()) {
      return get(view.getContext().getApplicationContext());
    }

    //通过view的context查找Activity
    Activity activity = findActivity(view.getContext());
    //如果activity为null, 说明context可能不是一个Activity,默认创建一个与Application绑定的RequestManager实例
    if (activity == null) {
      return get(view.getContext().getApplicationContext());
    }

    //如果是FragmentActivity
    if (activity instanceof FragmentActivity) {
      //通过view和FragmentActivity尝试查找SupportFragment
      Fragment fragment = findSupportFragment(view, (FragmentActivity) activity);
      //如果是SupportFragment不为null,就调用传入SupportFragment参数的get方法
      //为null就通过FragmentActivity参数的get方法获得
      return fragment != null ? get(fragment) : get((FragmentActivity) activity);
    }
    android.app.Fragment fragment = findFragment(view, activity);
    if (fragment == null) {//fragment为null
      return get(activity);//采用传入Activity参数的get方法获得
    }
    //fragment不为null
    return get(fragment);//采用传入android.app.Fragment参数的get方法获得
  }

通过上面get方法分析得到,如果传入的参数是Activityandroid.app.Fragment就会调用fragmentGet方法获取RequestManager实例,如果传入的参数是android.support.v4.FragmentFragmentActivity 会调用supportFragmentGet方法获取RequestManager实例。

先来分析下fragmentGet方法,supportFragmentGet方法同理

//fragmentGet方法
private RequestManager fragmentGet(
      @NonNull Context context,
      @NonNull android.app.FragmentManager fm,
      @Nullable android.app.Fragment parentHint,
      boolean isParentVisible) {
    //通过传入android.app.FragmentManager调用getRequestManagerFragment返回一个RequestManagerFragment。
    RequestManagerFragment current = getRequestManagerFragment(fm, parentHint, isParentVisible);
    //RequestManagerFragment已经保存了requestManager就直接获取
    RequestManager requestManager = current.getRequestManager();
    //如果是第一次创建RequestManagerFragment,那么requestManager为null
    if (requestManager == null) {
      Glide glide = Glide.get(context);
      //通过RequestManagerFactory的build方法创建一个RequestManager实例对象,注意这里的current.getGlideLifecycle()就是ActivityFragmentLifecycle实例
      requestManager = factory.build(glide, current.getGlideLifecycle(), current.getRequestManagerTreeNode(), context);
      //并把新创建的requestManager实例保存在RequestManagerFragment中,以便下次调用可以复用
      current.setRequestManager(requestManager);
    }
    //最后返回requestManager对象
    return requestManager;
  }

//通过传入android.app.FragmentManager调用getRequestManagerFragment方法创建一个新的空白的RequestManagerFragment
  private RequestManagerFragment getRequestManagerFragment(
      @NonNull final android.app.FragmentManager fm,
      @Nullable android.app.Fragment parentHint,
      boolean isParentVisible) {
    //首先通过FRAGMENT_TAG查找可复用的RequestManagerFragment
    RequestManagerFragment current = (RequestManagerFragment) fm.findFragmentByTag(FRAGMENT_TAG);
    //如果找不到
    if (current == null) {
     //尝试从pendingRequestManagerFragments的HashMap中获取
      current = pendingRequestManagerFragments.get(fm);
      //如果还是找不到
      if (current == null) {
        //就创建一个新的RequestManagerFragment
        current = new RequestManagerFragment();
        //设置父Fragment, 如果没有,parentHint为null
        current.setParentFragmentHint(parentHint);
        //如果父Activity或Fragment是可见的,那么手动触发onStart的调用
        if (isParentVisible) {
          current.getGlideLifecycle().onStart();
        }
        //把新创建的RequestManagerFragment以FragmentManager为key,RequestManagerFragment为value存入到pendingRequestManagerFragments
        pendingRequestManagerFragments.put(fm, current);
        //最后把新创建的RequestManagerFragment加入到FragmentManager中
        fm.beginTransaction().add(current, FRAGMENT_TAG).commitAllowingStateLoss();
        //注意: 这里通过Handler发送remove掉刚刚加入到pendingRequestManagerFragments中的RequestManagerFragment, 如果在一个Fragment里多次调用Glide.with().因为commitAllowingStateLoss之后,并不能立马findFragmentByTag找到,所以作者需要先把它存起来,等能找到的时候再将它移出去.
        handler.obtainMessage(ID_REMOVE_FRAGMENT_MANAGER, fm).sendToTarget();
      }
    }
    return current;
  }


//handleMessage
  @Override
  public boolean handleMessage(Message message) {
    boolean handled = true;
    Object removed = null;
    Object key = null;
    switch (message.what) {
      case ID_REMOVE_FRAGMENT_MANAGER:
        android.app.FragmentManager fm = (android.app.FragmentManager) message.obj;
        key = fm;
        removed = pendingRequestManagerFragments.remove(fm);//从pendingRequestManagerFragments中移除RequestManagerFragment
        break;
      case ID_REMOVE_SUPPORT_FRAGMENT_MANAGER:
        FragmentManager supportFm = (FragmentManager) message.obj;
        key = supportFm;
        removed = pendingSupportRequestManagerFragments.remove(supportFm);//从pendingSupportRequestManagerFragments中移除RequestManagerFragment
        break;
      default:
        handled = false;
        break;
    }
    if (handled && removed == null && Log.isLoggable(TAG, Log.WARN)) {
      Log.w(TAG, "Failed to remove expected request manager fragment, manager: " + key);
    }
    return handled;
  }

我们知道了创建好的RequestManager实例会保存在空白的RequestManagerFragmentSupportRequestManagerFragment。为什么会创建空白的Fragment呢?实际上这就是Glide生命周期绑定的设计巧妙之处,创建好的空白Fragment会被加入到FragmentManager中统一管理,这样一来空白的Fragment生命周期就能同步所在Activity生命周期了。 然后RequestManagerFragmentSupportRequestManagerFragment是怎么通知RequestManager的呢?我们知道为了性能和网络请求优化,对于生命周期结束时可以暂停中断网络请求,从而优化网络请求资源。

  //RequestManagerFragment构造器,内部创建了一个ActivityFragmentLifecycle生命周期管理者对象
  public RequestManagerFragment() {
    this(new ActivityFragmentLifecycle());
  }

  @VisibleForTesting
  @SuppressLint("ValidFragment")
  RequestManagerFragment(@NonNull ActivityFragmentLifecycle lifecycle) {
    this.lifecycle = lifecycle;
  }

然后一起来看下ActivityFragmentLifecycle内部实现, 内部维护一个Set<LifecycleListener> 然后每一个RequestManager就是一个LifecycleListener. 当Fragment生命周期触发onStart、onStop、onDestroy时,会调用ActivityFragmentLifecycle中的onStart、onStop、onDestroy方法。最后ActivityFragmentLifecycle中的onStart、onStop、onDestroy内部会遍历整个Set<LifecycleListener> 依次回调onStart、onStop、onDestroy方法。

class ActivityFragmentLifecycle implements Lifecycle {
//创建一个Set<LifecycleListener>用于存储所有需要同步生命周期的RequestManager
  private final Set<LifecycleListener> lifecycleListeners =
      Collections.newSetFromMap(new WeakHashMap<LifecycleListener, Boolean>());
  private boolean isStarted;
  private boolean isDestroyed;
  //addListener添加LifecycleListener
  @Override
  public void addListener(@NonNull LifecycleListener listener) {
    lifecycleListeners.add(listener);
    //如果此时的生命周期已经是isDestroyed、isStarted或isStop了那么新加入的listener会立即触发当前生命周期的回调
    if (isDestroyed) {
      listener.onDestroy();
    } else if (isStarted) {
      listener.onStart();
    } else {
      listener.onStop();
    }
  }

//removeListener删除LifecycleListener
  @Override
  public void removeListener(@NonNull LifecycleListener listener) {
    lifecycleListeners.remove(listener);
  }

//onStart
  void onStart() {
    //标识了此时生命周期已经是start了,isStarted为true
    isStarted = true;
    //遍历Set集合中所有lifecycleListener,通知触发它们的onStart方法
    for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
      lifecycleListener.onStart();
    }
  }
//onStop
  void onStop() {
  //标识了此时生命周期已经是stop了,isStarted为false
    isStarted = false;
    //遍历Set集合中所有lifecycleListener,通知触发它们的onStop方法
    for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
      lifecycleListener.onStop();
    }
  }
//onDestroy 销毁
  void onDestroy() {
  //标识了此时生命周期已经是Destroyed了,isDestroyed为true
    isDestroyed = true;
    //遍历Set集合中所有lifecycleListener,通知触发它们的onDestroy方法
    for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
      lifecycleListener.onDestroy();
    }
  }
}

我们知道了在RequestManagerFragment、SupportRequestManagerFragment创建的时候,会在内部创建一个ActivityFragmentLifecycle, 然后在其内部维护着一个Set<LifecycleListener>, 可以addremove监听。创建好空白Fragment后我们知道就会创建RequestManager对象。我们知道创建RequestManager对象是借助RequestManagerFactory中的build方法,先再来一起回顾这个方法的调用

//通过RequestManagerFactory的build方法创建一个RequestManager实例对象,注意这里的current.getGlideLifecycle()就是ActivityFragmentLifecycle实例
 requestManager = factory.build(glide, current.getGlideLifecycle(), current.getRequestManagerTreeNode(), context);
  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) {
            //lifecycle传入到RequestManager构造器中
          return new RequestManager(glide, lifecycle, requestManagerTreeNode, context);
        }
      };
public class RequestManager
    implements ComponentCallbacks2, LifecycleListener, ModelTypes<RequestBuilder<Drawable>> {//可以看到RequestManager实现了LifecycleListener,也就是每个RequestManager实例就是一个LifecycleListener
...
  RequestManager(
      Glide glide,
      Lifecycle lifecycle,
      RequestManagerTreeNode treeNode,
      RequestTracker requestTracker,
      ConnectivityMonitorFactory factory,
      Context context) {
    this.glide = glide;
    this.lifecycle = lifecycle;
    this.treeNode = treeNode;
    this.requestTracker = requestTracker;
    this.context = context;

    connectivityMonitor =
        factory.build(
            context.getApplicationContext(),
            new RequestManagerConnectivityListener(requestTracker));

    if (Util.isOnBackgroundThread()) {
      mainHandler.post(addSelfToLifecycle);
    } else {
      //注意: 这里lifecycle就是ActivityFragmentLifecycle实例,也就是通过factory.build方法传入的RequestManagerFragment中的ActivityFragmentLifecycle
      //这样一来RequestManager就把自己作为LifecycleListener注册到RequestManagerFragment中的ActivityFragmentLifecycle中了。
      lifecycle.addListener(this);
    }
    lifecycle.addListener(connectivityMonitor);
    defaultRequestListeners =
        new CopyOnWriteArrayList<>(glide.getGlideContext().getDefaultRequestListeners());
    setRequestOptions(glide.getGlideContext().getDefaultRequestOptions());

    glide.registerRequestManager(this);
  }        
    }

最后,RequestManagerFragmentSupportRequestManagerFragment的生命周期随着所在Activity生命周期同步时,触发它们生命周期回调的。然后在RequestManagerFragmentSupportRequestManagerFragment内部触发ActivityFragmentLifecycle实例的onStart、onStop、onDestroy的回调,最后又会触发它内部的Set<LifecycleListener>的回调,最后终于触发到所有注册进来的RequestManager的生命周期的回调。

public class RequestManagerFragment extends Fragment {
    private final ActivityFragmentLifecycle lifecycle;
     RequestManagerFragment(@NonNull ActivityFragmentLifecycle lifecycle) {
    this.lifecycle = lifecycle;
  }
  ...
    @Override
  public void onStart() {
    super.onStart();
    lifecycle.onStart();//触发ActivityFragmentLifecycle的onStart
  }

  @Override
  public void onStop() {
    super.onStop();
    lifecycle.onStop();//触发ActivityFragmentLifecycle的onStop
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    lifecycle.onDestroy();//触发ActivityFragmentLifecycle的onDestroy
    unregisterFragmentWithRoot();
  }
  ...
}

调用流程:

loading-ag-8671


   转载规则


《Glide源码分析之生命周期绑定(一)》 mikyou 采用 知识共享署名 4.0 国际许可协议 进行许可。
 上一篇
文本引擎框架(TextEngine)渲染迁移至WebView文本渲染 文本引擎框架(TextEngine)渲染迁移至WebView文本渲染
由TextEngine原生渲染迁移至WebView渲染 一、背景现状应项目需要在原有渲染技术基础上(支持普通文本渲染、图片渲染、链接等,渲染元素过于单一)扩展支持音频、视频等丰富功能。Android因为基于自身开发的TextEngine(基
2019-12-21
下一篇 
计算机网络面试题 计算机网络面试题
计算机网络相关面试题1、网络分层 OSI七层模型OSI七层协议模型主要是: 应用层(Application) 表示层(Presentation) 会话层(Session) 传输层(Transport) 网络层(Network) 数据链路层(
2019-12-10