新版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();
    }
}
相关推荐
工程师老罗11 分钟前
Android笔试面试题AI答之Android基础(1)
android
qq_397562312 小时前
android studio更改应用图片,和应用名字。
android·ide·android studio
峥嵘life2 小时前
Android Studio版本升级那些事
android·ide·android studio
新手上路狂踩坑2 小时前
Android Studio的笔记--BusyBox相关
android·linux·笔记·android studio·busybox
TroubleMaker4 小时前
OkHttp源码学习之retryOnConnectionFailure属性
android·java·okhttp
叶羽西6 小时前
Android Studio IDE环境配置
android·ide·android studio
发飙的蜗牛'6 小时前
23种设计模式
android·java·设计模式
花追雨16 小时前
Android -- 双屏异显之方法一
android·双屏异显
小趴菜822716 小时前
安卓 自定义矢量图片控件 - 支持属性修改矢量图路径颜色
android
氤氲息16 小时前
Android v4和v7冲突
android