How to get total RAM size of a device?

2019-01-08 22:08发布

问题:

I want to get full RAM size of a device. memoryInfo.getTotalPss() returns 0. There is not function for get total RAM size in ActivityManager.MemoryInfo.

How to do this?

回答1:

Standard unix command: $ cat /proc/meminfo

Note that /proc/meminfo is a file. You don't actually have to run cat, you can simply read the file.



回答2:

As of API level 16 you can now use the totalMem property of the MemoryInfo class.

Like this:

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

Api level 15 and lower still requires to use the unix command as shown in cweiske's answer.



回答3:

I can get the usable RAM memory in such a way

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;
}

Tested Upto Android 4.3 : SAMSUNG S3



回答4:

You can get the total RAM size by using this code:

var activityManager = GetSystemService(Activity.ActivityService) as ActivityManager;
var memoryInfo = new ActivityManager.MemoryInfo();
activityManager.GetMemoryInfo(memoryInfo);

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

If the device has 1GB RAM, totalRam will be 1000.



标签: android size ram