Android:ComponentCallbacks/ComponentCallbacks2与glide

ComponentCallbacks/ComponentCallbacks2类关系图

ComponentCallbacks
    ComponentCallbacks2 (android.content)
        Fragment (android.app)
        Glide (com.bumptech.glide)
        Application (android.app)
        Service (android.app)
        Activity (android.app)
            ListActivity (android.app)
            ComponentActivity (androidx.core.app)
            AliasActivity (android.app)
            NativeActivity (android.app)
            AccountAuthenticatorActivity (android.accounts)
            ActivityGroup (android.app)
            ExpandableListActivity (android.app)
        ContentProvider (android.content)
    Fragment (androidx.fragment.app)
        SupportRequestManagerFragment (com.bumptech.glide.manager)
        ListFragment (androidx.fragment.app)
        PickerFragment (com.google.android.material.datepicker)
        RxPermissionsFragment (com.tbruyelle.rxpermissions2)
        DialogFragment (androidx.fragment.app)
            AppCompatDialogFragment (androidx.appcompat.app)
            MaterialDatePicker (com.google.android.material.datepicker)

一、ComponentCallbacks

//这组回调的API,
// 适用于所有应用程序组件
// (的android.app.Activity , android.app.Service , ContentProvider ,和android.app.Application )。
// 注意:您也应该实现ComponentCallbacks2接口,
// 它提供了ComponentCallbacks2.onTrimMemory回调,以帮助您的应用程序更有效地管理其内存使用情况。
public interface ComponentCallbacks {
    //通过在设备配置您的组件运行时改变了系统调用。 
    // 需要注意的是,不同的活动,其他组件从未当配置更改重新启动:他们必须应对变化的结果,如再获取资源。
    //  在这个函数被调用的时候,你的资源对象将被更新,以返回匹配新的配置资源的值
    void onConfigurationChanged(@NonNull Configuration newConfig);

    //这是当整个系统运行在内存不足,并积极运行的进程应修剪其内存使用调用。 
    //虽然没有定义在此将被称为确切点,通常当所有的后台进程已被杀害它会发生。 
    //也就是说,达到了托管服务和前台UI杀死进程的点之前,我们想避免杀害。
    //您应该实现此方法来释放你可能持有的任何缓存或其他不必要的资源。 
    // 该系统将从此方法返回后执行垃圾收集你。
    //最好,你应该实现ComponentCallbacks2.onTrimMemory
    // 从ComponentCallbacks2根据不同级别的内存需求逐步卸下你的资源。 
    // 该API可用于API级别14和更高的,
    // 所以你应该只使用这个onLowMemory方法,旧版本的回退,
    // 可以治疗一样ComponentCallbacks2.onTrimMemory与ComponentCallbacks2.TRIM_MEMORY_COMPLETE水平。
    void onLowMemory();
}

二、ComponentCallbacks2

public interface ComponentCallbacks2 extends ComponentCallbacks {

    /** @hide */
    @IntDef(prefix = { "TRIM_MEMORY_" }, value = {
            TRIM_MEMORY_COMPLETE,
            TRIM_MEMORY_MODERATE,
            TRIM_MEMORY_BACKGROUND,
            TRIM_MEMORY_UI_HIDDEN,
            TRIM_MEMORY_RUNNING_CRITICAL,
            TRIM_MEMORY_RUNNING_LOW,
            TRIM_MEMORY_RUNNING_MODERATE,
    })
    @Retention(RetentionPolicy.SOURCE)
    public @interface TrimMemoryLevel {}

    /**
     * Level for {@link #onTrimMemory(int)}: the process is nearing the end
     * of the background LRU list, and if more memory isn't found soon it will
     * be killed.
     */
    static final int TRIM_MEMORY_COMPLETE = 80;
    
    /**
     * Level for {@link #onTrimMemory(int)}: the process is around the middle
     * of the background LRU list; freeing memory can help the system keep
     * other processes running later in the list for better overall performance.
     */
    static final int TRIM_MEMORY_MODERATE = 60;
    
    /**
     * Level for {@link #onTrimMemory(int)}: the process has gone on to the
     * LRU list.  This is a good opportunity to clean up resources that can
     * efficiently and quickly be re-built if the user returns to the app.
     */
    static final int TRIM_MEMORY_BACKGROUND = 40;
    
    /**
     * Level for {@link #onTrimMemory(int)}: the process had been showing
     * a user interface, and is no longer doing so.  Large allocations with
     * the UI should be released at this point to allow memory to be better
     * managed.
     */
    static final int TRIM_MEMORY_UI_HIDDEN = 20;

    /**
     * Level for {@link #onTrimMemory(int)}: the process is not an expendable
     * background process, but the device is running extremely low on memory
     * and is about to not be able to keep any background processes running.
     * Your running process should free up as many non-critical resources as it
     * can to allow that memory to be used elsewhere.  The next thing that
     * will happen after this is {@link #onLowMemory()} called to report that
     * nothing at all can be kept in the background, a situation that can start
     * to notably impact the user.
     */
    static final int TRIM_MEMORY_RUNNING_CRITICAL = 15;

    /**
     * Level for {@link #onTrimMemory(int)}: the process is not an expendable
     * background process, but the device is running low on memory.
     * Your running process should free up unneeded resources to allow that
     * memory to be used elsewhere.
     */
    static final int TRIM_MEMORY_RUNNING_LOW = 10;

    /**
     * Level for {@link #onTrimMemory(int)}: the process is not an expendable
     * background process, but the device is running moderately low on memory.
     * Your running process may want to release some unneeded resources for
     * use elsewhere.
     */
    static final int TRIM_MEMORY_RUNNING_MODERATE = 5;

    //当操作系统已经确定,这是一个好时机的过程,从它的过程中修剪不必要的内存调用。 
    // 当它在后台并没有足够的内存来保持如所需运行多个后台进程会发生这种情况,例如。 
    // 你不应该比较水平的精确值,因为可以添加新的中间值 - 你通常要比较值是否大于或等于你有兴趣在一个水平。
    // 为了获取任何一点处理当前配置级别,
    // 你可以使用ActivityManager.getMyMemoryState(RunningAppProcessInfo)
    void onTrimMemory(@TrimMemoryLevel int level);
}

ComponentCallbacks2接口扩展自ComponentCallbacks回调接口,用以实现更细粒度的内存管理。

此接口在所有应用程序组件(Activity,Service,ContentProvider和Application)中都可用。

您应该实现onTrimMemory(int)以根据当前系统约束逐步释放内存。
使用此回调来释放资源有助于提供整体响应更快的系统,同时通过允许系统使您的进程保持更长时间,直接有益于您的应用程序的用户体验。

也就是说,如果您不根据此回调定义的内存级别修剪资源,系统更有可能在最近最少使用(LRU)列表中缓存进程时终止您的进程,因此需要重新启动应用程序 并在用户返回时恢复所有状态。

  • 是一个细粒度的内存回收管理回调。
  • Application、Activity、Service、ContentProvider、Fragment实现了ComponentCallback2接口
  • 开发者应该实现onTrimMemory(int)方法,细粒度release 内存,参数可以体现不同程度的内存可用情况
  • 响应onTrimMemory回调:开发者的app会直接受益,有利于用户体验,系统更有可能让app存活的更持久。
  • 不响应onTrimMemory回调:系统更有可能kill 进程
当你的应用程序正在运行:
  • TRIM_MEMORY_RUNNING_MODERATE

设备开始运行缓慢,当前app正在运行,不会被kill

  • TRIM_MEMORY_RUNNING_LOW

设备运行更缓慢了,当前app正在运行,不会被kill。但是请回收unused资源,以便提升系统的性能。

  • TRIM_MEMORY_RUNNING_CRITICAL

设备运行特别慢,当前app还不会被杀死,但是如果此app没有释放资源,系统将会kill后台进程

当你的应用的可见性变化:
  • TRIM_MEMORY_UI_HIDDEN

当前app UI不再可见,这是一个回收大个资源的好时机,

当你的应用程序的过程中驻留在后台LRU列表:
  • TRIM_MEMORY_BACKGROUND

系统运行慢,并且进程位于LRU list的上端。尽管app不处于高风险被kill。当前app应该释放那些容易恢复的资源

  • TRIM_MEMORY_MODERATE

系统运行缓慢,当前进程已经位于LRU list的中部,如果系统进一步变慢,便会有被kill的可能

  • TRIM_MEMORY_COMPLETE

系统运行慢,当前进程是第一批将被系统kill的进程。此app应该释放一切可以释放的资源。低于api 14的,用户可以使用onLowMemory回调。

三、glide源码:

trim : 修剪

public class Glide implements ComponentCallbacks2 {

  //..........

  @Override
  public void onTrimMemory(int level) {
    trimMemory(level);
  }

  @Override
  public void onConfigurationChanged(Configuration newConfig) {
    // Do nothing.
  }

  @Override
  public void onLowMemory() {
    clearMemory();
  }

  public void clearMemory() {
    // Engine asserts this anyway when removing resources, fail faster and consistently
    Util.assertMainThread();
    // memory cache needs to be cleared before bitmap pool to clear re-pooled Bitmaps too. See #687.
    memoryCache.clearMemory();
    bitmapPool.clearMemory();
    arrayPool.clearMemory();
  }

  public void trimMemory(int level) {
    // Engine asserts this anyway when removing resources, fail faster and consistently
    Util.assertMainThread();
    // memory cache needs to be trimmed before bitmap pool to trim re-pooled Bitmaps too. See #687.
    memoryCache.trimMemory(level);
    bitmapPool.trimMemory(level);
    arrayPool.trimMemory(level);
  }


}

memoryCache 的清理策略
  public void clearMemory() {
    trimToSize(0);
  }
  
  public void trimMemory(int level) {
      if (level >= android.content.ComponentCallbacks2.TRIM_MEMORY_BACKGROUND) {
        // Entering list of cached background apps
        // Evict our entire bitmap cache
        clearMemory();
      } else if (level >= android.content.ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
          || level == android.content.ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL) {
        // The app's UI is no longer visible, or app is in the foreground but system is running
        // critically low on memory
        // Evict oldest half of our bitmap cache
        trimToSize(getMaxSize() / 2);
      }
  }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值