How to get total RAM size of a device?

前端 未结 5 526
囚心锁ツ
囚心锁ツ 2020-12-01 08:20

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.

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-01 08:35

    Simple method to get the total and available RAM are given below:

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

    Hope this will work.

    For formatting the value to KB and MB, the following method can be used :

    /**
         * 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. Unit of input value is assumed as bytes.
         * @return String the formatted value. e.g for input value 1024 it will return 1KB.
         * 

    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.

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

    The method body can be customised to get desirable results.

提交回复
热议问题