新版Glide检测生命周期原理

本文章使用的是glide 4.15.1

java 复制代码
public class RequestManagerRetriever implements Handler.Callback {
    rivate final LifecycleRequestManagerRetriever lifecycleRequestManagerRetriever;
    public RequestManagerRetriever(@Nullable RequestManagerFactory factory, GlideExperiments experiments) {//构造函数
  this.factory = factory != null ? factory : DEFAULT_FACTORY;
  lifecycleRequestManagerRetriever = new LifecycleRequestManagerRetriever(this.factory);
}
    @NonNull
public RequestManager get(@NonNull FragmentActivity activity) {
  if (Util.isOnBackgroundThread()) {
    return get(activity.getApplicationContext());
  }
  assertNotDestroyed(activity);
  frameWaiter.registerSelf(activity);
  boolean isActivityVisible = isActivityVisible(activity);
  Glide glide = Glide.get(activity.getApplicationContext());
  return lifecycleRequestManagerRetriever.getOrCreate(
      activity,
      glide,
      activity.getLifecycle(),//关键代码
      activity.getSupportFragmentManager(),
      isActivityVisible);
}
}

final class LifecycleRequestManagerRetriever {
  @Synthetic final Map<Lifecycle, RequestManager> lifecycleToRequestManager = new HashMap<>();
  @NonNull private final RequestManagerFactory factory;

  LifecycleRequestManagerRetriever(@NonNull RequestManagerFactory factory) {
    this.factory = factory;
  }
  RequestManager getOrCreate(
    Context context,
    Glide glide,
    final Lifecycle lifecycle,//关键代码,这个是上面的activity.getLifecycle()
    FragmentManager childFragmentManager,
    boolean isParentVisible) {
  Util.assertMainThread();
  RequestManager result = getOnly(lifecycle);
  if (result == null) {
    LifecycleLifecycle glideLifecycle = new LifecycleLifecycle(lifecycle);//关键代码
    result =
        factory.build(
            glide,
            glideLifecycle,//在这里面会创建RequestManager并把它加入glideLifecycle里面
            new SupportRequestManagerTreeNode(childFragmentManager),
            context);
    lifecycleToRequestManager.put(lifecycle, result);
    glideLifecycle.addListener(
        new LifecycleListener() {
          @Override
          public void onStart() {}

          @Override
          public void onStop() {}

          @Override
          public void onDestroy() {
            lifecycleToRequestManager.remove(lifecycle);
          }
        });
    // This is a bit of hack, we're going to start the RequestManager, but not the
    // corresponding Lifecycle. It's safe to start the RequestManager, but starting the
    // Lifecycle might trigger memory leaks. See b/154405040
    if (isParentVisible) {
      result.onStart();
    }
  }
  return result;
}
}


//LifecycleLifecycle.java
final class LifecycleLifecycle implements Lifecycle, LifecycleObserver {
  @NonNull
  private final Set<LifecycleListener> lifecycleListeners = new HashSet<LifecycleListener>();

  @NonNull private final androidx.lifecycle.Lifecycle lifecycle;

  LifecycleLifecycle(androidx.lifecycle.Lifecycle lifecycle) {
    this.lifecycle = lifecycle;
    lifecycle.addObserver(this);//关键代码,把自己嵌入到了activity.getLifecycle(),当生命周期函数有变化时就会通过它的onStart(),onStop(),onDestroy()
  }

  @OnLifecycleEvent(Event.ON_START)
  public void onStart(@NonNull LifecycleOwner owner) {
    for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
      lifecycleListener.onStart();
    }
  }

  @OnLifecycleEvent(Event.ON_STOP)
  public void onStop(@NonNull LifecycleOwner owner) {
    for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
      lifecycleListener.onStop();
    }
  }

  @OnLifecycleEvent(Event.ON_DESTROY)
  public void onDestroy(@NonNull LifecycleOwner owner) {
    for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
      lifecycleListener.onDestroy();
    }
    owner.getLifecycle().removeObserver(this);
  }

  @Override
  public void addListener(@NonNull LifecycleListener listener) {
    lifecycleListeners.add(listener);

    if (lifecycle.getCurrentState() == State.DESTROYED) {
      listener.onDestroy();
    } else if (lifecycle.getCurrentState().isAtLeast(State.STARTED)) {
      listener.onStart();
    } else {
      listener.onStop();
    }
  }

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


LifecycleLifecycle把会把RequestManager加入它的列表中,以便有生命周期函数变化时就通过它
LifecycleRequestManagerRetriever.java中
    LifecycleLifecycle glideLifecycle = new LifecycleLifecycle(lifecycle);//关键代码
    result =
        factory.build(
            glide,
            glideLifecycle,//在这里面会创建RequestManager并把它加入glideLifecycle里面
            new SupportRequestManagerTreeNode(childFragmentManager),
            context);
//RequestManagerRetriever.java中的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);//关键代码
      }
    };

public class RequestManager
    implements ComponentCallbacks2, LifecycleListener, ModelTypes<RequestBuilder<Drawable>> {
        
            public RequestManager(
    @NonNull Glide glide,
    @NonNull Lifecycle lifecycle,
    @NonNull RequestManagerTreeNode treeNode,
    @NonNull Context context) {
  this(
      glide,
      lifecycle,//关键代码
      treeNode,
      new RequestTracker(),
      glide.getConnectivityMonitorFactory(),
      context);
}

// Our usage is safe here.
@SuppressWarnings("PMD.ConstructorCallsOverridableMethod")
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));

  glide.registerRequestManager(this);
  if (Util.isOnBackgroundThread()) {
    Util.postOnUiThread(addSelfToLifecycle);
  } else {
    lifecycle.addListener(this);//关键代码
  }
  lifecycle.addListener(connectivityMonitor);

  defaultRequestListeners =
      new CopyOnWriteArrayList<>(glide.getGlideContext().getDefaultRequestListeners());
  setRequestOptions(glide.getGlideContext().getDefaultRequestOptions());
}
    
    }

然后再由RequestManager的onStart(),onStop(),onDestroy()去通过相应的RequestTracker requestTracker和TargetTracker targetTracker做对应的处理

java 复制代码
public class RequestManager
    implements ComponentCallbacks2, LifecycleListener, ModelTypes<RequestBuilder<Drawable>> {
  @SuppressWarnings("WeakerAccess")
  @Synthetic
  final Lifecycle lifecycle;

  @GuardedBy("this")
  private final RequestTracker requestTracker;

  @GuardedBy("this")
  private final TargetTracker targetTracker = new TargetTracker();
@Override
public synchronized void onStart() {
  resumeRequests();//关键代码
  targetTracker.onStart();//关键代码
}

@Override
public synchronized void onStop() {
  pauseRequests();//关键代码
  targetTracker.onStop();//关键代码
}

@Override
public synchronized void onDestroy() {
  targetTracker.onDestroy();//关键代码
  for (Target<?> target : targetTracker.getAll()) {
    clear(target);
  }
  targetTracker.clear();//关键代码
  requestTracker.clearRequests();//关键代码
  lifecycle.removeListener(this);//关键代码
  lifecycle.removeListener(connectivityMonitor);//关键代码
  Util.removeCallbacksOnUiThread(addSelfToLifecycle);
  glide.unregisterRequestManager(this);
}
}

总结:

总流程:Activity.getLifecycle()在LifecycleLifecycle构造函数里把LifecycleLifecycle this对象加入了Activity.getLifecycle(),LifecycleLifecycle对象传入RequestManager构造函数时,把RequestManager对象加入到了LifecycleLifecycle对象的监听列表里面,RequestManager对象又有RequestTracker和TargetTracker对象,有点饶,我写个抽象类(只为了看)

java 复制代码
public class ComponentActivity{
    private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
    //如上会通过Activity.getLifecycle().addObserver()方法加入到LifecycleLifecycle.this
}

public cliass LifecycleLifecycle{
    @NonNull
    private final Set<LifecycleListener> lifecycleListeners = new HashSet<LifecycleListener>();
    @Override
    public void addListener(@NonNull LifecycleListener listener) {
      lifecycleListeners.add(listener);
    }
    //LifecycleLifecycle会通过addListener()方法把RequestManager.this加入到lifecycleListeners
    @OnLifecycleEvent(Event.ON_START)
    public void onStart(@NonNull LifecycleOwner owner) {
      for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
        lifecycleListener.onStart();//RequestManager.this在里面,会被通知到
      }
    }
    
    @OnLifecycleEvent(Event.ON_STOP)
    public void onStop(@NonNull LifecycleOwner owner) {
      for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
        lifecycleListener.onStop();//RequestManager.this在里面,会被通知到
      }
    }
    
    @OnLifecycleEvent(Event.ON_DESTROY)
    public void onDestroy(@NonNull LifecycleOwner owner) {
      for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
        lifecycleListener.onDestroy();//RequestManager.this在里面,会被通知到
      }
      owner.getLifecycle().removeObserver(this);
    }
}

public class RequestManager implements LifecycleListener {
    private final RequestTracker requestTracker;
    private final TargetTracker targetTracker = new TargetTracker();
    
    @Override
    public synchronized void onStart() {
      resumeRequests();
      targetTracker.onStart();
    }
    
    @Override
    public synchronized void onStop() {
      pauseRequests();
      targetTracker.onStop();
    }

    @Override
    public synchronized void onDestroy() {
      targetTracker.onDestroy();
      targetTracker.clear();
      requestTracker.clearRequests();
    }
}
相关推荐
_祝你今天愉快29 分钟前
分析android :The binary version of its metadata is 1.8.0, expected version is 1.5.
android
暮志未晚Webgl1 小时前
109. UE5 GAS RPG 实现检查点的存档功能
android·java·ue5
麦田里的守望者江1 小时前
KMP 中的 expect 和 actual 声明
android·ios·kotlin
Dnelic-1 小时前
解决 Android 单元测试 No tests found for given includes:
android·junit·单元测试·问题记录·自学笔记
佛系小嘟嘟2 小时前
Android Studio不显示需要的tag日志解决办法《All logs entries are hidden by the filter》
android·ide·android studio
mariokkm2 小时前
Django一分钟:django中收集关联对象关联数据的方法
android·django·sqlite
长亭外的少年2 小时前
如何查看 Android 项目的依赖结构树
android
深海呐4 小时前
Android 从本地选择视频,用APP播放或进行其他处理
android·音视频·从本地选择视频,用app播放·从本地选择视频,并拿到信息·跳转到本地视频列表
深海呐4 小时前
Android Google登录接入
android·google登录接入·android 谷歌登录接入·google登录·android google
daiyang123...5 小时前
MySQL【知识改变命运】11
android·数据库·mysql