新版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();
    }
}
相关推荐
帅得不敢出门6 小时前
安卓设备adb执行AT指令控制电话卡
android·adb·sim卡·at指令·电话卡
我又来搬代码了7 小时前
【Android】使用productFlavors构建多个变体
android
德育处主任9 小时前
Mac和安卓手机互传文件(ADB)
android·macos
芦半山9 小时前
Android“引用们”的底层原理
android·java
迃-幵10 小时前
力扣:225 用队列实现栈
android·javascript·leetcode
大风起兮云飞扬丶10 小时前
Android——从相机/相册获取图片
android
Rverdoser10 小时前
Android Studio 多工程公用module引用
android·ide·android studio
aaajj10 小时前
[Android]从FLAG_SECURE禁止截屏看surface
android
@OuYang11 小时前
android10 蓝牙(二)配对源码解析
android
Liknana11 小时前
Android 网易游戏面经
android·面试