如何获得设备的总RAM大小?

BOO*_*Mik 22 size ram android

我想获得一个设备的完整RAM大小.memoryInfo.getTotalPss()返回0.没有获取总RAM大小的函数ActivityManager.MemoryInfo.

这该怎么做?

Leo*_*die 36

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

像这样:

ActivityManager actManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
actManager.getMemoryInfo(memInfo);
long totalMemory = memInfo.totalMem;
Run Code Online (Sandbox Code Playgroud)

Api等级15和更低仍需要使用unix命令,如cweiske的答案所示.


cwe*_*ske 19

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

请注意,这/proc/meminfo是一个文件.你实际上不必运行cat,你可以简单地读取文件.


Shi*_*din 19

我可以用这种方式获得可用的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;
}
Run Code Online (Sandbox Code Playgroud)

测试Upto Android 4.3:SAMSUNG S3


Bru*_*ein 5

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

var ActivityManager = GetSystemService(Activity.ActivityService) 作为 ActivityManager;
var memoryInfo = new ActivityManager.MemoryInfo();
ActivityManager.GetMemoryInfo(内存信息);

var TotalRam = memoryInfo.TotalMem / (1024 * 1024);

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