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

Vivek Warde
  • 1,936
  • 8
  • 47
  • 77
  • 1
    Related: http://stackoverflow.com/questions/3170691/how-to-get-current-memory-usage-in-android – shyam Oct 10 '14 at 09:10

2 Answers2

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;
  • percentAvail is always 0 using above, probably should be: `float percentAvail = Math.round(100.0 * (double)mi.availMem / (double)mi.totalMem);` – Greg Ennis May 30 '17 at 17:26
  • You need to cast to double for the percentAvail to work as intended. `double percentAvail = (double) mi.availMem / mi.totalMem;` – Nelson Almendra Apr 20 '18 at 16:44
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;
} 
Suresh Parmar
  • 815
  • 7
  • 15