通过ComponentCallbacks2来接收onTrimMemory等回调,并mock对应的场景

1,977 阅读2分钟

我们在做app内存不足时,需要做一些内存释放的操作,以避免app卡顿,或者尽可能的延迟app存活时间,减少被系统回收的概率。

如何监听ComponentCallbacks

那么如何监听这些时机呢?系统的Application、Activity、Service和ContentProvider均实现了ComponentCallbacks2接口,我们可以很方便的获取这些时机。除了这些时机之外,我们还可以通过Context#registerComponentCallbacks来添加自己的监听器。

一般而言我们添加ComponentCallbacks2即可,ComponentCallbacks2不仅有onTrimMemory(@TrimMemoryLevel int level)方法,,它还继承了ComponentCallbacks接口,所以也能监听到系统的onConfigurationChanged(@NonNull Configuration newConfig)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 {}

    static final int TRIM_MEMORY_COMPLETE = 80;

    static final int TRIM_MEMORY_MODERATE = 60;
    
    static final int TRIM_MEMORY_BACKGROUND = 40;

    static final int TRIM_MEMORY_UI_HIDDEN = 20;

    static final int TRIM_MEMORY_RUNNING_CRITICAL = 15;

    static final int TRIM_MEMORY_RUNNING_LOW = 10;

    static final int TRIM_MEMORY_RUNNING_MODERATE = 5;

    void onTrimMemory(@TrimMemoryLevel int level);
}

ComponentCallbacks源码:

public interface ComponentCallbacks {

    void onConfigurationChanged(@NonNull Configuration newConfig);

    void onLowMemory();
}

如何mock这些时机呢?

网上那些杀掉进程的操作千篇一律,而且也不能mock所有的时机,所以这里不予采纳。

经过不懈的查找,我找到一个可以mockonTrimMemory(@TrimMemoryLevel int level)方法中所有level的命令,具体格式如下:

adb shell am send-trim-memory <package-name> <level>

e.g.: level可以是常量字符串也可以是对应的数字,跟ComponentCallbacks2.TrimMemoryLevel中的值一一对应

adb shell am send-trim-memory com.tinytongtong.androidstudy MODERATE

或者:

adb shell am send-trim-memory com.tinytongtong.androidstudy 5

level具体映射关系如表格所示:

TrimMemoryLevellevel对应的字符串常量level对应的数字
TRIM_MEMORY_COMPLETECOMPLETE80
TRIM_MEMORY_MODERATEMODERATE60
TRIM_MEMORY_BACKGROUNDBACKGROUND40
TRIM_MEMORY_UI_HIDDENHIDDEN20
TRIM_MEMORY_RUNNING_CRITICALRUNNING_CRITICAL15
TRIM_MEMORY_RUNNING_LOWRUNNING_LOW10
TRIM_MEMORY_RUNNING_MODERATERUNNING_MODERATE5

全部命令的示例:

adb shell am send-trim-memory com.tinytongtong.androidstudy COMPLETE

adb shell am send-trim-memory com.tinytongtong.androidstudy MODERATE

adb shell am send-trim-memory com.tinytongtong.androidstudy BACKGROUND

adb shell am send-trim-memory com.tinytongtong.androidstudy HIDDEN

adb shell am send-trim-memory com.tinytongtong.androidstudy RUNNING_CRITICAL

adb shell am send-trim-memory com.tinytongtong.androidstudy RUNNING_LOW

adb shell am send-trim-memory com.tinytongtong.androidstudy RUNNING_MODERATE

参考

stackoverflow.com/questions/3…