【问题标题】:What's the best way to detect Low memory?检测内存不足的最佳方法是什么?
【发布时间】:2018-07-16 14:14:15
【问题描述】:

我正在为 android 构建一个库,并试图通过在内存不足时禁用某些功能来避免 OutOfMemory 错误

对此我有两种解决方案,但实际上我很困惑哪个更好

第一个是在ActivityManager.MemoryInfo 中使用lowMemory 布尔值,这给出了整个系统内存的指示

public static boolean isLowMemory(Context context) {
    if (context != null) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();

        if (activityManager != null) {
            activityManager.getMemoryInfo(memoryInfo);
            return memoryInfo.lowMemory;
        }
    }

    return true;
}

另一种方法是使用Runtime

public static boolean isLowMemory() {
    final Runtime runtime = Runtime.getRuntime();
    final long usedMemInMB = (runtime.totalMemory() - runtime.freeMemory()) / 1048576L;
    final long maxHeapSizeInMB = runtime.maxMemory() / 1048576L;
    final long availHeapSizeInMB = maxHeapSizeInMB - usedMemInMB;
    return availHeapSizeInMB < 10;
}

我相信这个应该获得应用程序本身的内存,但我担心的是,如果 Ram 仍然有空白空间,堆大小将继续扩展,这意味着堆可能仍然可以扩展分配的内存,但我没有不知道这是否可能。

你怎么看?

【问题讨论】:

  • 我认为你最好解决任何导致 OOM 异常的问题
  • Application类中还有onTrimMemory。但蒂姆是对的。 Youtube 上有一些关于“跑步 -> 个人资料”的好视频。此外,“分析 -> 检查代码”可以揭示许多常见的内存泄漏。
  • 我的问题是我的 android 库通常在不是我的应用程序中运行。他们中很少有人有糟糕的内存使用,这也会影响我的图书馆。我想添加一个防御性代码,让我在内存不足时停止密集的工作。
  • 正如@TimCastelijns 所建议的,您必须对您的库进行概要分析。我认为无论你问什么都是不可暗示的。
  • @mnagy,你是怎么解决你的问题的?

标签: android android-library android-memory


【解决方案1】:

您可以检查 activityManager.isLowRamDevice() 函数以及 memoryInfo.lowMemory 。这会给你一个指示

【讨论】:

    猜你喜欢
    • 2016-10-25
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-08
    • 2019-09-05
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    相关资源
    最近更新 更多