private static double readCPURate() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("/proc/stat")), 1000);
String load = reader.readLine();
reader.close();
String[] cpuInfos = load.split(" ");
long currTotal = Long.parseLong(cpuInfos[2]) + Long.parseLong(cpuInfos[3]) + Long.parseLong(cpuInfos[4]);
long currIdle = Long.parseLong(cpuInfos[5]);
cpuUsageRate = (currTotal - cpuTotalTime) * 100.0f / (currTotal - cpuTotalTime + currIdle - cpuIdleTime);
cpuTotalTime = currTotal;
cpuIdleTime = currIdle;
} catch (IOException ex) {
ex.printStackTrace();
}
return cpuUsageRate;
}
public static void getCurrentCPURate(final onCPURateListener CPURate) {
TaskHelper.exec(new TaskHelper.Task() {
int cpuRate;
@Override
public void execute() throws Exception {
readCPURate();
SystemClock.sleep(300);
double firstCPUUsage = readCPURate();
SystemClock.sleep(300);
double secondCPUUsage = readCPURate();
cpuRate = (int) Math.round((firstCPUUsage + secondCPUUsage) / 2.0f);
}
@Override
public void callback(Exception e) {
if (CPURate != null)
CPURate.getCPURate(cpuRate);
}
});
}
Android获取CPU使用率
最新推荐文章于 2024-06-26 15:43:45 发布