Android gets device running memory information

Unit Conversion GB and GiB

Be sure to note that the conversion is 1000, not 1024

1GB = 1,000,000 KB
1GiB = 1,024MiB = 1,048,576 KiB

ADB view

➜  ~ adb shell cat /proc/meminfo
MemTotal:       11871600 kB
MemFree:          442120 kB
MemAvailable:    7564364 kB

getMemoryInfo() in ActivityManager

ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
MemoryInfo memInfo = new MemoryInfo();//存放内存信息的对象
activityManager.getMemoryInfo(memInfo);//传入参数,将获得数据保存在memInfo对象中
long availMem = memInfo.availMem/1000000;//可用内存
long totalMem = memInfo.totalMem/1000000;//总内存

read /proc/meminfo

    /**
     *   获取android总运行内存大小
     *  
     */
    public static String getTotalMemory() {
    
    
        String str1 = "/proc/meminfo";// 系统内存信息文件
        String str2;
        String[] arrayOfString;
        long initial_memory = 0;
        try {
    
    
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);
            str2 = localBufferedReader.readLine();// 读取meminfo第一行,系统总内存大小
            arrayOfString = str2.split("\\s+");
            for (String num : arrayOfString) {
    
    
                Log.i(str2, num + "\t");
            }
            // 获得系统总内存,单位是KB
            int i = Integer.valueOf(arrayOfString[1]).intValue();
            //int值乘以1024转换为long类型
            initial_memory = new Long((long) i * 1024);
            localBufferedReader.close();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        return Formatter.formatFileSize(MyApplication.getInstance(), initial_memory);// Byte转换为KB或者MB,内存大小规格化
    }

Measured

running memory

8GB手机:7.52
12GB手机:12.15

reference

https://www.jianshu.com/p/7190f56af9e1
https://www.jianshu.com/p/b26e3615f2ae
https://developer.aliyun.com/article/707949
https://www.zhihu.com/question/24601215/answer/28341062
https://weiwangqiang.github.io/2019/03/23/android-file-size-formatter/

Guess you like

Origin blog.csdn.net/b1tb1t/article/details/131290808