get Memory Used Percent Value - Android android.os

Android examples for android.os:Memory

Description

get Memory Used Percent Value

Demo Code

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import android.app.ActivityManager;
import android.content.Context;

public class Main {

  public static int getMemoryUsedPercentValue(Context context) {
    String dir = "/proc/meminfo";
    try {//  ww  w  . ja v  a 2  s . c o m
      FileReader fr = new FileReader(dir);
      BufferedReader br = new BufferedReader(fr, 2048);
      String memoryLine = br.readLine();
      String subMemoryLine = memoryLine.substring(memoryLine.indexOf("MemTotal:"));
      br.close();
      long totalMemorySize = Integer.parseInt(subMemoryLine.replaceAll("\\D+", ""));
      long availableSize = getAvailableMemory(context) / 1024;
      int percent = (int) ((totalMemorySize - availableSize) / (float) totalMemorySize * 100);
      return percent;
    } catch (IOException e) {
      e.printStackTrace();
    }
    return 0;
  }

  private static long getAvailableMemory(Context context) {
    ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    activityManager.getMemoryInfo(mi);
    return mi.availMem;
  }

}

Related Tutorials