ComponentCallbacks2 的 onTrimMemory() 没有被调用

onTrimMemory() from ComponentCallbacks2 does not get called

我已经实现了 ComponentCallbacks2 并且永远不会调用 onTrimMemory。我正在尝试使用应用程序 class 和我的自定义生命周期来管理内存。对此的任何帮助表示赞赏。

public class MemoryManager implements ComponentCallbacks2 {
    private static List<MemoryInfo> memInfoList = new ArrayList<>();

    public interface MemoryInfo {
        void releaseMemory();
    }

    public static void registerMemoryListener(MemoryInfo memoryInfo) {
        memInfoList.add(memoryInfo);
    }

    public static void unregisterMemoryListener(MemoryInfo memoryInfo) {
        memInfoList.remove(memoryInfo);
    }

    @Override
    public void onTrimMemory(int level) {
        Log.i("TEST", "onTrimMemory called"); // does not get called
        switch (level) {
            case ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW:
                try {
                    for (int i = memInfoList.size() - 1; i >= 0; i--) {
                        try {
                            memInfoList.get(i).releaseMemory(); // is this correct implementation?
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN:
                // I added logs here, it does not get reached
                break;
            default:
                break;
        }
    }

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

    @Override
    public void onLowMemory() {
        // will log when there is log memory
    }

我有一个应用程序 class 从 MemoryManager class 调用我的接口。

public class TestApplication extends Application implements ActivityLifecycleCallback, MemoryManager.MemoryInfo {

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onStart(Activity activity) {
        Log.i(TAG, "onStart() called :: " + activity.getLocalClassName());
    }

    @Override
    public void onResume(Activity activity) {
        Log.i(TAG, "onResume called :: " + activity.getLocalClassName());
        MemoryManager.registerMemoryListener(this);
    }

    @Override
    public void onPause(Activity activity) {
        Log.i(TAG, "onPause called :: " + activity.getLocalClassName());
    }

    @Override
    public void onStop(Activity activity) {
        Log.i(TAG, "onStop called :: " + activity.getLocalClassName());
        MemoryManager.unregisterMemoryListener(this);
    }

    @Override
    public void onDestroy(Activity activity) {
        Log.i(TAG, "onDestroy called :: " + activity.getLocalClassName());
    }

    @Override
    public void releaseMemory() {
        Log.i(TAG, "releaseMemory() called");
    }

我的主要 Activity 只是跟踪生命周期。这工作正常。我的生命周期方法如下所示:

@Override
protected void onDestroy() {
    // register lifecycle
    application.onDestroy(activity);
    super.onDestroy();
}

@Override
protected void onPause() {
    // register lifecycle
    application.onPause(activity);
    super.onPause();
}

@Override
protected void onResume() {
    // register lifecycle
    application.onResume(activity);
    super.onResume();
}

@Override
protected void onStart() {
    // register lifecycle
    application.onStart(activity);
    super.onStart();
}

我错过了什么来调用 onTrimMemory()?

如果您查看 the documentation for ComponentCallbacks2,您会注意到它已经在 类 上实现,就像 ApplicationActivity 一样。因此,对于那些组件,欢迎您只覆盖 onTrimMemory(),它将被适当地调用。

这应该允许您从问题中删除几乎所有代码。

你不应该实现 ComponentCallbacks2,如果想使用 onTrimMemory(),你应该在你的应用程序 class 中覆盖 onTrimMemory()。但是如果你真的想在你的自定义 class 中正确使用它,请使用 registerComponentCallbacks(ComponentCallbacks callback)

如果您想开始跟踪活动生命周期,可以使用 registerActivityLifecycleCallbacks(callback);

回调是实现了Application.ActivityLifecycleCallbacks

的Applicationclass

例如,你可以在你的应用程序的OnCreate方法中注册它class。

也许这对其他人来说是显而易见的,但对我来说我浪费了很多时间在没有澄清这一点的答案上:onTrimMemory 在整个 SYSTEM 低时被调用,而不是你的应用程序。好吧,当您的应用进入后台以释放 UI 资源时,它也会被调用,但这与本次讨论无关。

您的应用程序可能 运行 在系统认为自身总体内存不足之前分配给其 JVM 的内存不足。

要确定您的应用程序是否内存不足,您需要查看 JVM 的内存分配。这很简单:

long maxMem = Runtime.getRuntime().maxMemory();
long totalMem = Runtime.getRuntime().totalMemory();
long freeMem = Runtime.getRuntime().freeMemory();
long totalFreeMem = maxMem - totalMem + freeMem;

if (totalFreeMem < (maxMem * 0.2f)) {
    // I'm using 20% as my threshold for "low memory".  Use a value appropriate for your application.
}

totalFreeMem 需要进行该计算,因为 totalMemory() 只是当前分配给您的 JVM 的内存总量,可能小于允许的 maxMemory()。而 freeMemory() 是当前分配的内存中的空闲内存量,不在允许的最大值内。

不幸的是,这意味着没有自动回调方法可以知道您的 JVM 何时内存不足(据我所知),因此您需要在知道内存的代码的各个部分进行低内存检查经常被消耗并酌情释放它。

当然,您也可能遇到系统性能低但您的应用程序的 JVM 性能低的情况,因此您仍然希望适当地实现 onTrimMemory 和释放内存。虽然我认为对于您的 JVM 来说,这种情况很少见,但它有足够的内存并且系统认为它总体上很低。