首页 > 代码库 > 系统内存信息获取工具类

系统内存信息获取工具类

/**
 * 得到系统内存信息的工具类
 * @author zwenkai
 */
public class SystemInfoUtils {
    /**
     * 得到运行的进程总个数
     * 
     * @param context
     * @return 运行进程个数
     */
    public static int getRunningProcessCount(Context context) {
	ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
	return am.getRunningAppProcesses().size();
    }
    /**
     * 得到可用内存数
     * 
     * @param context
     * @return
     */
    public static long getAvailRam(Context context) {
	ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
	MemoryInfo outInfo = new MemoryInfo();
	am.getMemoryInfo(outInfo);
	return outInfo.availMem;
    }
    /**
     * 得到总内存数
     * 
     * @param context
     * @return
     */
	
    public static long getTotalRam(Context context) {
	try {
	    File file = new File("/proc/meminfo");
	    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
	    String line = br.readLine();
	    br.close();
	    StringBuffer sb = new StringBuffer();
	    //MemTotal:         513000 kB
	    for (char c :line.toCharArray()) {
	        if(c > ‘0‘ && c < ‘9‘) {
		    sb.append(c);
		}
	    }
	    return Integer.parseInt(sb.toString())*1024l;
	} catch (IOException e) {
	    e.printStackTrace();
	    return 0;
	}
    }
	
    //4.0之后可以使用
    public long getTotalRam1(Context context) {
	ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
	MemoryInfo outInfo = new MemoryInfo();
	am.getMemoryInfo(outInfo);
	return outInfo.totalMem;
    }
}