Glide系列 -- 与Activity关联关系

分析版本为glide:4.9.0

时序图


Glide与Activity生命周期相关联

with方法

  • with(Context context)
  • with(Activity activity)
  • with(FragmentActivity activity)
  • with(android.app.Fragment fragment)
  • with(Fragment fragment)// v4包下
  • with(View view)

所有这些with方法,首先都会根据传入的值获取到ApplicationContext,生成Glide对象,并获取RequestManagerRetriever对象

根据代码分析下

首先得到Glide对象 --initializeGlide(@NonNull Context context, @NonNull GlideBuilder builder)方法

 @SuppressWarnings("deprecation")
  private static void initializeGlide(@NonNull Context context, @NonNull GlideBuilder builder) {
    // with方法根据不同的传值获取其上下文 获取到全局的上下文
    Context applicationContext = context.getApplicationContext();
    // 获取注解GlideModule的类 如果没有自定义的GlideModule则,返回null
    GeneratedAppGlideModule annotationGeneratedModule = getAnnotationGeneratedGlideModules();
    List<com.bumptech.glide.module.GlideModule> manifestModules = Collections.emptyList();
    // 获取AndroidManifest.xml中meta-data中配置的GlideModule
    if (annotationGeneratedModule == null || annotationGeneratedModule.isManifestParsingEnabled()) {
      manifestModules = new ManifestParser(applicationContext).parse();
    }
    // 删除manifestModules中与注解GlideModule重复的module
    if (annotationGeneratedModule != null
        && !annotationGeneratedModule.getExcludedModuleClasses().isEmpty()) {
      Set<Class<?>> excludedModuleClasses =
          annotationGeneratedModule.getExcludedModuleClasses();
      Iterator<com.bumptech.glide.module.GlideModule> iterator = manifestModules.iterator();
      while (iterator.hasNext()) {
        com.bumptech.glide.module.GlideModule current = iterator.next();
        if (!excludedModuleClasses.contains(current.getClass())) {
          continue;
        }
        if (Log.isLoggable(TAG, Log.DEBUG)) {
          Log.d(TAG, "AppGlideModule excludes manifest GlideModule: " + current);
        }
        iterator.remove();
      }
    }
    ... // 输出log,无关代码
    // 获取RequestManagerFactory对象 如果没有自定义的GlideModule则为null
    RequestManagerRetriever.RequestManagerFactory factory =
        annotationGeneratedModule != null
            ? annotationGeneratedModule.getRequestManagerFactory() : null;
    builder.setRequestManagerFactory(factory);
    for (com.bumptech.glide.module.GlideModule module : manifestModules) {
      module.applyOptions(applicationContext, builder);
    }
    if (annotationGeneratedModule != null) {
      annotationGeneratedModule.applyOptions(applicationContext, builder);
    }
    // 生成Glide对象
    Glide glide = builder.build(applicationContext);
    for (com.bumptech.glide.module.GlideModule module : manifestModules) {
      module.registerComponents(applicationContext, glide, glide.registry);
    }
    if (annotationGeneratedModule != null) {
      annotationGeneratedModule.registerComponents(applicationContext, glide, glide.registry);
    }
    applicationContext.registerComponentCallbacks(glide);
    Glide.glide = glide;
  }

第二步,获取RequestManagerRetriever对象
这步很简单,我们在生成Glide对象的时候就已经生成的RequestManagerRetriever对象
GlideBuilder的build方法

...
// 根据上面分析,我们如果没有写自定义GlideModule方法,requestManagerFactory为null
 RequestManagerRetriever requestManagerRetriever =
        new RequestManagerRetriever(requestManagerFactory);
 return new Glide(
        context,
        engine,
        memoryCache,
        bitmapPool,
        arrayPool,
        requestManagerRetriever,
        connectivityMonitorFactory,
        logLevel,
        defaultRequestOptions.lock(),
        defaultTransitionOptions,
        defaultRequestListeners,
        isLoggingRequestOriginsEnabled);
  }

RequestManagerRetriever.java

public RequestManagerRetriever(@Nullable RequestManagerFactory factory) {
    // 如果factory为空,使用默认的RequestManagerFactory
    this.factory = factory != null ? factory : DEFAULT_FACTORY;
    // 此处,我觉得很重要
    handler = new Handler(Looper.getMainLooper(), this /* Callback */);
  }

第三步,获取RequestManager对象

根据我们调用with方法传入的对象获取RequestManager对象

如果当前是后台线程,直接获取ApplicationContext处理

我们先来分析在当前UI线程

 @NonNull
  public RequestManager get(@NonNull Activity activity) {
    if (Util.isOnBackgroundThread()) {
      return get(activity.getApplicationContext());
    } else {
      assertNotDestroyed(activity);
      android.app.FragmentManager fm = activity.getFragmentManager();
      return fragmentGet(
          activity, fm, /*parentHint=*/ null, isActivityVisible(activity));
    }
  }
@Deprecated
  @NonNull
  private RequestManager fragmentGet(@NonNull Context context,
      @NonNull android.app.FragmentManager fm,
      @Nullable android.app.Fragment parentHint,
      boolean isParentVisible) {
      // 获取RequestManagerFragment
    RequestManagerFragment current = getRequestManagerFragment(fm, parentHint, isParentVisible);
    // 获取fragment中的requestManager
    RequestManager requestManager = current.getRequestManager();
    if (requestManager == null) {
      // TODO(b/27524013): Factor out this Glide.get() call.
      Glide glide = Glide.get(context);
      // 如果没有,则新建一个,并设置到fragment中
      // factory 如果我们没有自定的module设置的话,使用的是默认的factory
      requestManager =
          factory.build(
              glide, current.getGlideLifecycle(), current.getRequestManagerTreeNode(), context);
      current.setRequestManager(requestManager);
    }
    return requestManager;
  }

获取RequestManagerFragment

 @NonNull
  private RequestManagerFragment getRequestManagerFragment(
      @NonNull final android.app.FragmentManager fm,
      @Nullable android.app.Fragment parentHint,
      boolean isParentVisible) {
      // 先从FragmentManager中找看是否已经存在该fragment
    RequestManagerFragment current = (RequestManagerFragment) fm.findFragmentByTag(FRAGMENT_TAG);
    if (current == null)
    // 如果没有,则从我们自己的Map中找
      current = pendingRequestManagerFragments.get(fm);
      if (current == null) {
        // 如果都没有,则新建一个fragment 
        current = new RequestManagerFragment();
        current.setParentFragmentHint(parentHint);
        // 如果当前Activity没有isFinishing则isParentVisible为true
        if (isParentVisible) {
            // 触发lifecycle的onStart方法
          current.getGlideLifecycle().onStart();
        }
        //放入自己的map中
        pendingRequestManagerFragments.put(fm, current);
        // 开启事物,加tag 显示fragment
        fm.beginTransaction().add(current, FRAGMENT_TAG).commitAllowingStateLoss();
        handler.obtainMessage(ID_REMOVE_FRAGMENT_MANAGER, fm).sendToTarget();
      }
    }
    return current;
  }

获取requestManager对象 最终调用RequestManager的构造方法

RequestManager(
      Glide glide,
      Lifecycle lifecycle,
      RequestManagerTreeNode treeNode,
      RequestTracker requestTracker,
      ConnectivityMonitorFactory factory,
      Context context) {
    this.glide = glide;
    // lifecycle 为fragment中的ActivityFragmenLifecycle对象
    this.lifecycle = lifecycle;
    this.treeNode = treeNode;
    // 请求追踪器  requestTracker = new RequestTracker()
    this.requestTracker = requestTracker;
    this.context = context;
    // 连接的监听器
    connectivityMonitor =
        factory.build(
            context.getApplicationContext(),
            new RequestManagerConnectivityListener(requestTracker));

    // If we're the application level request manager, we may be created on a background thread.
    // In that case we cannot risk synchronously pausing or resuming requests, so we hack around the
    // issue by delaying adding ourselves as a lifecycle listener by posting to the main thread.
    // This should be entirely safe.
    if (Util.isOnBackgroundThread()) {
      mainHandler.post(addSelfToLifecycle);
    } else {
        // 如果不是后台线程,则添加listener
      lifecycle.addListener(this);
    }
    // 添加连接监听器
    lifecycle.addListener(connectivityMonitor);

    defaultRequestListeners =
        new CopyOnWriteArrayList<>(glide.getGlideContext().getDefaultRequestListeners());
    setRequestOptions(glide.getGlideContext().getDefaultRequestOptions());
    
    // 把requestManager注册到glide中
    glide.registerRequestManager(this);
  }

当我们所在的Activity执行onStop()方法之后,所关联的fragment也会执行onStop()方法

RequestManagerFragment.java

public void onStop() {
    super.onStop();
    // lifecycle为ActivityFragmentLifecycle
    lifecycle.onStop();
  }

ActivityFragmentLifecycle.java

void onStop() {
    isStarted = false;
    //迭代注册的listener 执行onStop方法
    // 一个listener为RequestManager
    // 一个为connectivityMonitor
    for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
      lifecycleListener.onStop();
    }
  }

RequestManager.java

public synchronized void onStop() {
    pauseRequests();
    targetTracker.onStop();
  }
  
  public synchronized void pauseRequests() {
    // requestTracker 为RequestTracker对象 在RequestManager构造函数中创建
    requestTracker.pauseRequests();
  }

RequestTracker.java

/**
   * Stops any in progress requests. 停止任何正在进行的请求
   */
public void pauseRequests() {
    isPaused = true;
    for (Request request : Util.getSnapshot(requests)) {
      if (request.isRunning()) {
        request.clear();
        // 将请求加入list
        pendingRequests.add(request);
      }
    }
  }

到此,页面onStop后,Glide不在加载

同理 页面onStart()恢复之后
RequestTracker.java

/**
   * Starts any not yet completed or failed requests. 
   * 开始没有完成或者失败的请求
   */
  public void resumeRequests() {
    isPaused = false;
    for (Request request : Util.getSnapshot(requests)) {
      // We don't need to check for cleared here. Any explicit clear by a user will remove the
      // Request from the tracker, so the only way we'd find a cleared request here is if we cleared
      // it. As a result it should be safe for us to resume cleared requests.
      if (!request.isComplete() && !request.isRunning()) {
        request.begin();
      }
    }
    // 清空列表
    pendingRequests.clear();
  }

onDestory()

/**
   * Lifecycle callback that cancels all in progress requests and clears and recycles resources for
   * all completed requests.
   * 清空所有的请求,glide与RequestManager解除关系
   */
  @Override
  public synchronized void onDestroy() {
    targetTracker.onDestroy();
    for (Target<?> target : targetTracker.getAll()) {
      clear(target);
    }
    targetTracker.clear();
    requestTracker.clearRequests();
    lifecycle.removeListener(this);
    lifecycle.removeListener(connectivityMonitor);
    mainHandler.removeCallbacks(addSelfToLifecycle);
    glide.unregisterRequestManager(this);
  }