Подтвердить что ты не робот

Как получить общий объем оперативной памяти устройства?

Я хочу получить полный объем оперативной памяти устройства. memoryInfo.getTotalPss() возвращает 0. Не существует функции для получения полного объема оперативной памяти в ActivityManager.MemoryInfo.

Как это сделать?

4b9b3361

Ответ 1

Стандартная команда unix: $ cat /proc/meminfo

Обратите внимание, что /proc/meminfo - это файл. Вам действительно не нужно запускать cat, вы можете просто прочитать файл.

Ответ 2

Начиная с уровня 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;

Уровень Api 15 и ниже все еще требует использования команды unix, как показано в ответе cweiske.

Ответ 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;
}

Протестировано Upto Android 4.3: SAMSUNG S3

Ответ 4

Вы можете получить общий размер ОЗУ с помощью этого кода:

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

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

Если устройство имеет 1 ГБ ОЗУ, totalRam будет 1000.

Ответ 5

Простой способ получения общей и доступной оперативной памяти приведен ниже:

//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();

Надеюсь, это сработает.

Для форматирования значения в КБ и МБ можно использовать следующий метод:

/**
     * 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();
    }

Тело метода может быть настроено для получения желаемых результатов.