How to get current free RAM available in android device [duplicate]
Asked Answered
C

2

6

In a device when we go in Manage apps->running tab then at bottom we see the used memory & free memory live changing their value.

How can we code it to my app to display just the same statistics ?

Thanks

Cockade answered 10/10, 2014 at 8:51 Comment(1)
Related: #3171191Singularity
C
20

ActivityManager.MemoryInfo

MemoryInfo mi = new MemoryInfo();
ActivityManager activityManager = (ActivityManager)getActivity(). getSystemService(Context.ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
long availableMegs = mi.availMem / 1048576L;

long percentAvail = mi.availMem / mi.totalMem;
Coprolalia answered 10/10, 2014 at 9:11 Comment(2)
percentAvail is always 0 using above, probably should be: float percentAvail = Math.round(100.0 * (double)mi.availMem / (double)mi.totalMem);Hugo
You need to cast to double for the percentAvail to work as intended. double percentAvail = (double) mi.availMem / mi.totalMem;Wagner
A
1

You can get using this method.

private float readUsage() {
    try {
        RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
        String load = reader.readLine();

        String[] toks = load.split(" ");

        long idle1 = Long.parseLong(toks[4]);
        long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5])
              + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        try {
            Thread.sleep(360);
        } catch (Exception e) {}

        reader.seek(0);
        load = reader.readLine();
        reader.close();

        toks = load.split(" ");

        long idle2 = Long.parseLong(toks[4]);
        long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5])
            + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        return (float)(cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return 0;
} 
Amabel answered 10/10, 2014 at 9:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.