【问题标题】:How to know how much ram size my app needs?如何知道我的应用程序需要多少内存?
【发布时间】:2017-01-20 14:33:51
【问题描述】:

我是 android 新手,我的应用有时会生成 outOfMemoryException。因此,我必须检查我的应用程序正在使用多少内存并尝试减少它。

两个问题:

  1. 如何知道我的应用使用的内存大小?
  2. 通常,应用程序内存大小的安全阈值是多少,才不会导致outOfMemoryException

非常感谢您的帮助!

【问题讨论】:

  • 访问这里是很好的解释:stackoverflow.com/questions/2630158/…
  • 你什么时候收到OutOfMemory Exception?当您尝试在ImageView 上加载图像时,您是否收到此Exception
  • 是的,但奇怪的是,我在模拟器上运行时很少得到OutOfMemory Exception,而在手机上运行时总是得到OutOfMemory Exception
  • 在您的应用程序中,您是否在 ImageView 上加载了多个图像?还是在 ImageView 上加载大图?
  • 我正在 ImageView 上加载多个(大约 100 个)小图像,我正在访问 this page 试图解决问题。

标签: android memory out-of-memory


【解决方案1】:

查看 Android Studio 的内置 memory monitor。你会在下面找到 Android 监视器 > 监视器

对于问题的第二部分,您可以使用ActivtyManager class'getMemoryClass () 方法。 来自安卓文档..

返回当前设备的每个应用程序的近似内存类。这让您了解应该对应用程序施加多硬的内存限制以使整个系统发挥最佳作用。返回值以兆字节为单位;基准 Android 内存类是 16(恰好是这些设备的 Java 堆限制);一些内存更大的设备可能会返回 24 甚至更多的数字。

【讨论】:

    【解决方案2】:

    在尝试加载图像之前,请检查图像大小是否小于可用内存。因此,处理 OutOfMemoryException 最有效的方法是构建应用程序,使其永远不会尝试将大量数据加载到内存中以避免异常。

    在将图像加载到内存之前使用压缩图像

    Bitmap original = BitmapFactory.decodeStream(getAssets().open("1024x768.jpg"));
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    original.compress(Bitmap.CompressFormat.PNG, 100, out);
    Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
    
    Log.e("Original   dimensions", original.getWidth()+" "+original.getHeight());
    Log.e("Compressed dimensions", decoded.getWidth()+" "+decoded.getHeight());  
    

    【讨论】:

      【解决方案3】:

      1.如何知道我的应用使用的内存大小? 这个问题相当难回答。不同类型的应用需要不同的内存。

      2. 通常,应用程序的内存大小的安全阈值是多少,以使其不会导致 outOfMemoryException? 不同的设备有不同的阈值。可以正常使用

      Runtime rt=Runtime.getRuntime();
      long maxMemory=rt.maxMemory();
      Log.i("maxMemory:",Long.toString(maxMemory/(1024*1024)));
      

      查看可以使用的 maxMemory 大小。但这并不完全是。

      【讨论】:

        猜你喜欢
        • 2017-07-29
        • 1970-01-01
        • 2011-05-14
        • 1970-01-01
        • 2018-09-15
        • 2010-12-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多