1.获取cpu占用率
实现:通过读取proc文件
public static float getProcessCpuRate() {
float totalCpuTime1 = getTotalCpuTime();
float processCpuTime1 = getAppCpuTime();
try {
Thread.sleep(360); //sleep一段时间
} catch (Exception e) {
}
float totalCpuTime2 = getTotalCpuTime();
float processCpuTime2 = getAppCpuTime();
float cpuRate = 100 * (processCpuTime2 - processCpuTime1) / (totalCpuTime2 - totalCpuTime1);//百分比
return cpuRate;
}
// 获取系统总CPU使用时间
public static long getTotalCpuTime() {
String[] cpuInfos = null;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream("/proc/stat")), 1000);
String load = reader.readLine();
reader.close();
cpuInfos = load.split(" ");
} catch (IOException ex) {
ex.printStackTrace();
}
long totalCpu = Long.parseLong(cpuInfos[2])
+ Long.parseLong(cpuInfos[3]) + Long.parseLong(cpuInfos[4])
+ Long.parseLong(cpuInfos[6]) + Long.parseLong(cpuInfos[5])
+ Long.parseLong(cpuInfos[7]) + Long.parseLong(cpuInfos[8]);
return totalCpu;
}
// 获取应用占用的CPU时间
public static long getAppCpuTime() {
String[] cpuInfos = null;
try {
int pid = android.os.Process.myPid();
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream("/proc/" + pid + "/stat")), 1000);
String load = reader.readLine();
reader.close();
cpuInfos = load.split(" ");
} catch (IOException ex) {
ex.printStackTrace();
}
long appCpuTime = Long.parseLong(cpuInfos[13])
+ Long.parseLong(cpuInfos[14]) + Long.parseLong(cpuInfos[15])
+ Long.parseLong(cpuInfos[16]);
return appCpuTime;
}
2.获取内存占用
// 获取应用占用的内存(单位为KB)
public static String getAppMemory() {
String info = null;
try {
int pid = android.os.Process.myPid();
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream("/proc/" + pid + "/status")), 1000);
String load;
while ((load = reader.readLine()) != null) {
load = load.replace(" ", "");
String[] Info = load.split("[: k K]");
if (Info[0].equals("VmRSS")) {
info = Info[1];
break;
}
}
reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return info;
}
注意:android8.0以上读取proc文件权限在正式环境下会受到限制。必须由系统方将app加入白名单