【问题标题】:How to get total RAM size of a device?如何获取设备的总 RAM 大小?
【发布时间】:2011-11-14 12:17:42
【问题描述】:

我想获取设备的完整 RAM 大小。 memoryInfo.getTotalPss() 返回 0。ActivityManager.MemoryInfo 中没有获取 RAM 总大小的功能。

如何做到这一点?

【问题讨论】:

  • public static synchronized int readTotalRam() { int tm=1000; try { RandomAccessFile reader = new RandomAccessFile("/proc/meminfo", "r"); String load = reader.readLine(); String[] totrm = load.split(" kB"); String[] trm = totrm[0].split(" "); tm=Integer.parseInt(trm[trm.length-1]); tm=Math.round(tm/1024); } catch (IOException ex) { ex.printStackTrace(); } return tm; }
  • 我为此编写函数。 ^^^回答^^^

标签: android size ram


【解决方案1】:

从 API 级别 16 开始,您现在可以使用 MemoryInfo 类的 totalMem 属性。

像这样:

ActivityManager actManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
actManager.getMemoryInfo(memInfo);
long totalMemory = memInfo.totalMem;

API 15 级及以下仍需要使用 unix 命令,如cweiske's answer 所示。

【讨论】:

    【解决方案2】:

    标准 unix 命令:$ cat /proc/meminfo

    注意/proc/meminfo 是一个文件。您实际上不必运行cat,您只需读取文件即可。

    【讨论】:

    • 我重新读取 /proc/meminfo 文件并收到 ram 大小。
    • 回滚到这个答案的原作者版本。虽然 Leon 发布了一些适用于更高 API 级别的内容,但这并不意味着此方法不再有效。不应使用 3rd 方编辑来评论答案 - 这是 cmets 的角色,或者在这种情况下,是 Leon 自己的答案。
    • 另外,我将从设备上运行的代码中添加,没有理由运行 cat 进程 - 相反,只需从您的 java 或本机代码中读取 /proc/meminfo 就好像它一样是一个文本文件。仅当您在 shell 中工作或访问需要您在不同的用户 ID 下使用被黑的 su 启动进程的东西时才需要 Cat。
    【解决方案3】:

    我可以通过这种方式获得可用的RAM内存

    public String getTotalRAM() {
    
        RandomAccessFile reader = null;
        String load = null;
        DecimalFormat twoDecimalForm = new DecimalFormat("#.##");
        double totRam = 0;
        String lastValue = "";
        try {
            reader = new RandomAccessFile("/proc/meminfo", "r");
            load = reader.readLine();
    
            // Get the Number value from the string
            Pattern p = Pattern.compile("(\\d+)");
            Matcher m = p.matcher(load);
            String value = "";
            while (m.find()) {
                value = m.group(1);
                // System.out.println("Ram : " + value);
            }
            reader.close();
    
            totRam = Double.parseDouble(value);
            // totRam = totRam / 1024;
    
            double mb = totRam / 1024.0;
            double gb = totRam / 1048576.0;
            double tb = totRam / 1073741824.0;
    
            if (tb > 1) {
                lastValue = twoDecimalForm.format(tb).concat(" TB");
            } else if (gb > 1) {
                lastValue = twoDecimalForm.format(gb).concat(" GB");
            } else if (mb > 1) {
                lastValue = twoDecimalForm.format(mb).concat(" MB");
            } else {
                lastValue = twoDecimalForm.format(totRam).concat(" KB");
            }
    
    
    
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            // Streams.close(reader);
        }
    
        return lastValue;
    }
    

    测试到 Android 4.3:SAMSUNG S3

    【讨论】:

      【解决方案4】:

      您可以使用以下代码获取总 RAM 大小:

      var activityManager = GetSystemService(Activity.ActivityService) as ActivityManager;
      var memoryInfo = new ActivityManager.MemoryInfo();
      activityManager.GetMemoryInfo(memoryInfo);
      
      var totalRam = memoryInfo.TotalMem / (1024 * 1024);

      如果设备有 1GB RAM,totalRam 将为 1000。

      【讨论】:

      • 您的语法代码和方法在 java 中不正确。你的代码是用 C# 和 xamarin 编写的吗?
      • 是的,我发布它只是为了有一个基础。
      【解决方案5】:

      要获取 RAM 值,只需执行以下操作:

      ActivityManager actManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
          ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
          assert actManager != null;
          actManager.getMemoryInfo(memInfo);
          long totalMemory = memInfo.totalMem;
          long availMemory = memInfo.availMem;
          long usedMemory = totalMemory - availMemory;
          float precentlong = (((float) (availMemory / totalMemory)) * 100);
      

      在这里,您将获得 Total 以及 Free 和 Used RAM 大小。 这些值将是“long”,因此将其格式化为人类可读的(即 MB/GB)。 使用以下方法:

       private String floatForm(double d) {
          return String.format(java.util.Locale.US, "%.2f", d);
      }
      
      private String bytesToHuman(long size) {
          long Kb = 1024;
          long Mb = Kb * 1024;
          long Gb = Mb * 1024;
          long Tb = Gb * 1024;
          long Pb = Tb * 1024;
          long Eb = Pb * 1024;
      
          if (size < Kb) return floatForm(size) + " byte";
          if (size >= Kb && size < Mb) return floatForm((double) size / Kb) + " KB";
          if (size >= Mb && size < Gb) return floatForm((double) size / Mb) + " MB";
          if (size >= Gb && size < Tb) return floatForm((double) size / Gb) + " GB";
          if (size >= Tb && size < Pb) return floatForm((double) size / Tb) + " TB";
          if (size >= Pb && size < Eb) return floatForm((double) size / Pb) + " Pb";
          if (size >= Eb) return floatForm((double) size / Eb) + " Eb";
      
          return "0";
      }
      

      所以现在将这些值设置为任何文本视图:

      totalRam_tv.setText("".concat(bytesToHuman(totalMemory)));
      

      【讨论】:

        【解决方案6】:

        获取总内存和可用内存的简单方法如下:

        //Method call returns the free RAM currently and returned value is in bytes.
        Runtime.getRuntime().freeMemory();
        
        //Method call returns the total RAM currently and returned value is in bytes.
        Runtime.getRuntime().maxMemory();
        

        希望这会奏效。

        要将值格式化为 KB 和 MB,可以使用以下方法:

        /**
             * Method to format the given long value in human readable value of memory.
             * i.e with suffix as KB and MB and comma separated digits.
             *
             * @param size Total size in long to be formatted. <b>Unit of input value is assumed as bytes.</b>
             * @return String the formatted value. e.g for input value 1024 it will return 1KB.
             * <p> For the values less than 1KB i.e. same input value will return back. e.g. for input 900 the return value will be 900.</p>
             */
            private String formatSize(long size) {
                String suffix = null;
        
                if (size >= 1024) {
                    suffix = " KB";
                    size /= 1024;
                    if (size >= 1024) {
                        suffix = " MB";
                        size /= 1024;
                    }
                }
        
                StringBuilder resultBuffer = new StringBuilder(Long.toString(size));
        
                int commaOffset = resultBuffer.length() - 3;
                while (commaOffset > 0) {
                    resultBuffer.insert(commaOffset, ',');
                    commaOffset -= 3;
                }
        
                if (suffix != null) resultBuffer.append(suffix);
                return resultBuffer.toString();
            }
        

        可以自定义方法体以获得理想的结果。

        【讨论】:

        • Runtime.getRuntime().maxMemory() 在魅族 X8 上返回 256MB。这是不正确的。
        • 您是否在其他设备上测试过相同的代码?
        • 不,我保证只返回 Android 运行时某些部分使用的内存,而不是设备总内存。我切换到 Klein 的答案,发现它工作正常。
        猜你喜欢
        • 2013-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-29
        相关资源
        最近更新 更多