Glide 缓存和生命周期的相关介绍

312 阅读7分钟

这是我参与11月更文挑战的第9天,活动详情查看:2021最后一次更文挑战

Glide缓存介绍

默认情况下,Glide 会在开始一个新的图片请求之前检查以下多级的缓存:

  1. 活动资源 (Active Resources)
  2. 内存缓存 (Memory Cache)
  3. 资源类型(Resource Disk Cache)
  4. 原始数据 (Data Disk Cache)

活动资源:如果当前对应的图片资源正在使用,则这个图片会被Glide放入活动缓存。

内存缓存:如果图片最近被加载过,并且当前没有使用这个图片,则会被放入内存中

资源类型: 被解码后的图片写入磁盘文件中,解码的过程可能修改了图片的参数(如:inSampleSize、inPreferredConfig)

原始数据: 图片原始数据在磁盘中的缓存(从网络、文件中直接获得的原始数据)

获取图片的流程

image.png

Glide会首先从Active Resources查找当前是否有对应的活跃图片,没有则查找内存缓存,没有则查找资源类型,没有则查找数据来源。

活动资源

当需要加载某张图片能够从内存缓存中获得的时候,在图片加载时主动将对应图片从内存缓存中移除,加入到活动资源中。
这样也可以避免因为达到内存缓存最大值或者系统内存压力导致的内存缓存清理,从而释放掉活动资源中的图片(recycle)。
活动资源中是一个”引用计数"的图片资源的弱引用集合。

因为同一张图片可能在多个地方被同时使用,每一次使用都会将引用计数+1,而当引用计数为0时候,则表示这个图片没有被使用也就是没有强引用了。这样则会将图片从活动资源中移除,并加入内存缓存。

内存缓存

默认使用LRU(最近最少使用算法),当资源从活动资源移除的时候,会加入此缓存。使用图片的时候会主动从此缓存移除,加入活动资源。

在每次get/put的时候会判断数据是否达到了maxSize,如果达到则会优先删除tail尾端的数据。

资源类型,原始数据

统称磁盘缓存。缓存的是经过解码后的图片,如果再使用就不需要再去进行解码配置(BitmapFactory.Options),加快获得图片速度。 资源类型 缓存的图片再次使用的时候不需要计算缩放因子。 原始数据 缓存的是没有经过修改的图片。

Bitmap复用池

内存缓存中Bitmap是内存消耗的主要元凶,Glide是通过Bitmap的复用池进行缓存, BitmapPool缓存Bitmap 对象,避免重复创建Bitmap避免资源的过渡消耗。

LruBitmapPool是BitmapPool的实现类,可以通过Glide的配置项配置builder.setBitmapPool。LruBitmapPool没有做太多的东西主要任务都交给了 LruPoolStrategy缓存策略接口,具体的实现类有 AttributeStrategy、SizeConfigStrategy 和 SizeStrategy,这三个类是通过不同的条件来缓存 Bitmap 的,底层具体的实现都使用了GroupedLinkedMap

class GroupedLinkedMap<K extends Poolable, V> {
    private final GroupedLinkedMap.LinkedEntry<K, V> head = new GroupedLinkedMap.LinkedEntry();
    private final Map<K, GroupedLinkedMap.LinkedEntry<K, V>> keyToEntry = new HashMap();

    GroupedLinkedMap() {
    }

    //设置
    public void put(K key, V value) {
        GroupedLinkedMap.LinkedEntry<K, V> entry = (GroupedLinkedMap.LinkedEntry)this.keyToEntry.get(key);
        if (entry == null) {
            entry = new GroupedLinkedMap.LinkedEntry(key);
            this.makeTail(entry);
            this.keyToEntry.put(key, entry);
        } else {
            key.offer();
        }
        entry.add(value);
    }

    //读取
    @Nullable
    public V get(K key) {
        GroupedLinkedMap.LinkedEntry<K, V> entry = (GroupedLinkedMap.LinkedEntry)this.keyToEntry.get(key);
        if (entry == null) {
            entry = new GroupedLinkedMap.LinkedEntry(key);
            this.keyToEntry.put(key, entry);
        } else {
            key.offer();
        }
        this.makeHead(entry);
        return entry.removeLast();
    }
}

BitmapPool 大小通过 MemorySizeCalculator 设置,使用LRU算法维护BitmapPool,会根据 Bitmap 的大小与 Config 生成一个 Key,Key 也有自己对应的对象池,数据最终存储在GroupedLinkedMap 中,GroupedLinkedMap使用哈希表、循环链表、List 来存储数据。

生命周期管理

Glide.with(context)中就实现了生命周期管理,with根据传入的参数有不同的实现

  //传入一个Context
  public static RequestManager with(@NonNull Context context)
  //传入一个activity
  public static RequestManager with(@NonNull Activity activity)
  //传入一个FragmentActivity 
  public static RequestManager with(@NonNull FragmentActivity activity)
  //传入一个Fragment
  public static RequestManager with(@NonNull Fragment fragment)
  //传入一个View
  public static RequestManager with(@NonNull View view)

虽然有这么多类型,但其实可以分为两类的。

  • 传入一个ApplicationContext,Glide的生命周期就相当于绑定了整个应用,只要应用不退出,任何时候都能够加载,也可以理解为不对Glide生命周期进行管理。
  • 传入activity、FragmentActivity 、Fragment 及View ,这样就会创建一个看不见的fragment,Glide的生命周期就随着该Fragment的变化而变化。
当传入参数为ApplicationContext时
  public static RequestManager with(@NonNull Context context) {
    return getRetriever(context).get(context);
  }
  //由于传入参数是ApplicationContext,所以最终调用getApplicationManager方法。
  public RequestManager get(@NonNull Context context) {
    if (context == null) {
      throw new IllegalArgumentException("You cannot start a load on a null Context");
    } else if (Util.isOnMainThread() && !(context instanceof Application)) {
      if (context instanceof FragmentActivity) {
        //判断context类型是不是FragmentActivity
        return get((FragmentActivity) context);
      } else if (context instanceof Activity) {
        //判断context类型是不是Activity
        return get((Activity) context);
      } else if (context instanceof ContextWrapper) {
        //判断context类型是不是ContextWrapper
        return get(((ContextWrapper) context).getBaseContext());
      }
    }
    //context类型属于ApplicationContext
    return getApplicationManager(context);
  }
  
    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) {
          Glide glide = Glide.get(context.getApplicationContext());
          applicationManager =
              factory.build(
                  glide,
                  new ApplicationLifecycle(),
                  new EmptyRequestManagerTreeNode(),
                  context.getApplicationContext());
        }
      }
    }

    return applicationManager;
  }

这里就直接创建一个ApplicationLifecycle来管理生命周期,但ApplicationLifecycle并不受控制,所以就无法对Glide生命周期进行管理.

以传入参数类型为Activity为例
 public static RequestManager with(@NonNull Activity activity) {
    return getRetriever(activity).get(activity);
  }
  public RequestManager get(@NonNull Activity activity) {
    //如果在子线程,则不对Glide生命周期就那些管理
    if (Util.isOnBackgroundThread()) {
      return get(activity.getApplicationContext());
    } else {
      assertNotDestroyed(activity);
      //拿到FragmentManager对象
      android.app.FragmentManager fm = activity.getFragmentManager();
      //获取fragment对象,并返回一个RequestManager 对象
      return fragmentGet(
          activity, fm, /*parentHint=*/ null, isActivityVisible(activity));
    }

如果当前是在子线程,则不需要对Glide生命周期进行管理,否则将通过fragmentGet方法创建一个fragment

private RequestManager fragmentGet(@NonNull Context context,
      @NonNull android.app.FragmentManager fm,
      @Nullable android.app.Fragment parentHint,
      boolean isParentVisible) {
    //创建一个fragment对象
    RequestManagerFragment current = getRequestManagerFragment(fm, parentHint, isParentVisible);
    RequestManager requestManager = current.getRequestManager();
    if (requestManager == null) {
      // TODO(b/27524013): Factor out this Glide.get() call.
      //防止Glide对象被异常回收
      Glide glide = Glide.get(context);
      //创建一个RequestManager对象
      requestManager =
          factory.build(
              glide, current.getGlideLifecycle(), current.getRequestManagerTreeNode(), context);
      current.setRequestManager(requestManager);
    }
    return requestManager;
  }

在该方法中,通过getRequestManagerFragment来获得一个Fragment对象。然后拿到该Fragment对应的RequestManager 对象,如果该对象为null则创建一个RequestManager对象并将fragment中的ActivityFragmentLifecycle对象传递给RequestManager

先来看getRequestManagerFragment方法的实现。

  private RequestManagerFragment getRequestManagerFragment(
      @NonNull final android.app.FragmentManager fm,
      @Nullable android.app.Fragment parentHint,
      boolean isParentVisible) {
    //查找tag为FRAGMENT_TAG的fragment
    RequestManagerFragment current = (RequestManagerFragment) fm.findFragmentByTag(FRAGMENT_TAG);
    if (current == null) {
      //从HashMap中取出fm
      current = pendingRequestManagerFragments.get(fm);
      if (current == null) {
        //创建fragment对象
        current = new RequestManagerFragment();
        //当fragment嵌套fragment时才会使用,否则parentHint是null
        current.setParentFragmentHint(parentHint);
        if (isParentVisible) {
          //开始执行请求
          current.getGlideLifecycle().onStart();
        }
        //将fm添加到HashMap中,防止fragment的重复创建
        pendingRequestManagerFragments.put(fm, current);
        //添加fragment
        fm.beginTransaction().add(current, FRAGMENT_TAG).commitAllowingStateLoss();
        //从HashMap集合从移除fm
        handler.obtainMessage(ID_REMOVE_FRAGMENT_MANAGER, fm).sendToTarget();
      }
    }
    return current;
  }

pendingRequestManagerFragments主要是防止fragment重复创建,因为每个activity必须对应一个唯一的fragment

来看一下这个fragment的实现

public class RequestManagerFragment extends Fragment {
  private final ActivityFragmentLifecycle lifecycle;
  public SupportRequestManagerFragment() {
    this(new ActivityFragmentLifecycle());
  }
  public SupportRequestManagerFragment(@NonNull ActivityFragmentLifecycle lifecycle) {
    this.lifecycle = lifecycle;
  }
  ...
  @NonNull
  ActivityFragmentLifecycle getGlideLifecycle() {
    return lifecycle;
  }
  ...
  @Override
  public void onStart() {
    super.onStart();
    lifecycle.onStart();
  }

  @Override
  public void onStop() {
    super.onStop();
    lifecycle.onStop();
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    lifecycle.onDestroy();
    unregisterFragmentWithRoot();
  }
  ...
}

再回到fragmentGet方法,fragment创建成功后,在创建RequestManager时会传入fragment中的ActivityFragmentLifecycle,再来看RequestManager的实现。

public class RequestManager implements LifecycleListener,
    ModelTypes<RequestBuilder<Drawable>> {
  private final Runnable addSelfToLifecycle = new Runnable() {
    @Override
    public void run() {
      lifecycle.addListener(RequestManager.this);
    }
  };
  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;
    ...
    if (Util.isOnBackgroundThread()) {
      //当在子线程时通过Handler将当前对象注册到ActivityFragmentLifecycle
      mainHandler.post(addSelfToLifecycle);
    } else {
      //将当前对象注册到ActivityFragmentLifecycle
      lifecycle.addListener(this);
    }
    //网络变化监听
    lifecycle.addListener(connectivityMonitor);
    ...
  }
  //开始加载
  @Override
  public synchronized void onStart() {
    resumeRequests();
    //如果有动画则开始动画
    targetTracker.onStart();
  }
  //停止加载
  @Override
  public synchronized void onStop() {
    pauseRequests();
    //如果有动画则动画停止
    targetTracker.onStop();
  }
  //销毁
  @Override
  public synchronized void onDestroy() {
    //如果有动画则动画结束并销毁
    targetTracker.onDestroy();
    ...
  }
  //开始请求数据
  synchronized void track(@NonNull Target<?> target, @NonNull Request request) {
    targetTracker.track(target);
    requestTracker.runRequest(request);
  }
 ...
}

可以看见在RequestManager的构造函数将RequestManager注册到ActivityFragmentLifecycle中,再来看看ActivityFragmentLifecycle的实现。

class ActivityFragmentLifecycle implements Lifecycle {
  private final Set<LifecycleListener> lifecycleListeners =
      Collections.newSetFromMap(new WeakHashMap<LifecycleListener, Boolean>());
  private boolean isStarted;
  private boolean isDestroyed;
  @Override
  public void addListener(@NonNull LifecycleListener listener) {
    lifecycleListeners.add(listener);

    if (isDestroyed) {
      listener.onDestroy();
    } else if (isStarted) {
      listener.onStart();
    } else {
      listener.onStop();
    }
  }

  @Override
  public void removeListener(@NonNull LifecycleListener listener) {
    lifecycleListeners.remove(listener);
  }
  //每个RequestManager对应一个LifecycleListener 
  void onStart() {
    isStarted = true;
    for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
      lifecycleListener.onStart();
    }
  }
  //每个RequestManager对应一个LifecycleListener 
  void onStop() {
    isStarted = false;
    for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
      lifecycleListener.onStop();
    }
  }
  //每个RequestManager对应一个LifecycleListener 
  void onDestroy() {
    isDestroyed = true;
    for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
      lifecycleListener.onDestroy();
    }
  }
}

由于ActivityFragmentLifecycle对象是在fragment中创建并且它的onStart、onStop、onDestory方法与fragment一一对应,这样就将RequestManager的生命周期就与fragment关联起来了,也就与当前activity关联起来

小结

image.png

当fragment生命周期发生变化时,通过ActivityFragmentLifecycle将变化告诉给RequestManagerDefaultConnectivityMonitor。而RequestManager又将此变化告诉给ImageViewTarget