Ran*_*ku' 21 android processor cpu-usage performance-monitor
我想获得Android上的整体CPU使用率,类似于Windows的任务管理器.我可以解析topAndroid中包含的程序的输出,但如果有一个API调用做同样的事情,那就更好了.
有什么指针吗?
Fab*_*app 25
注意:这个答案是旧的,也不要在Android上的由于增强的安全机制较新版本.
要获得完整的CPU使用率(不适用于每个进程),您可以使用:
/**
*
* @return integer Array with 4 elements: user, system, idle and other cpu
* usage in percentage.
*/
private int[] getCpuUsageStatistic() {
String tempString = executeTop();
tempString = tempString.replaceAll(",", "");
tempString = tempString.replaceAll("User", "");
tempString = tempString.replaceAll("System", "");
tempString = tempString.replaceAll("IOW", "");
tempString = tempString.replaceAll("IRQ", "");
tempString = tempString.replaceAll("%", "");
for (int i = 0; i < 10; i++) {
tempString = tempString.replaceAll(" ", " ");
}
tempString = tempString.trim();
String[] myString = tempString.split(" ");
int[] cpuUsageAsInt = new int[myString.length];
for (int i = 0; i < myString.length; i++) {
myString[i] = myString[i].trim();
cpuUsageAsInt[i] = Integer.parseInt(myString[i]);
}
return cpuUsageAsInt;
}
private String executeTop() {
java.lang.Process p = null;
BufferedReader in = null;
String returnString = null;
try {
p = Runtime.getRuntime().exec("top -n 1");
in = new BufferedReader(new InputStreamReader(p.getInputStream()));
while (returnString == null || returnString.contentEquals("")) {
returnString = in.readLine();
}
} catch (IOException e) {
Log.e("executeTop", "error in getting first line of top");
e.printStackTrace();
} finally {
try {
in.close();
p.destroy();
} catch (IOException e) {
Log.e("executeTop",
"error in closing and destroying top process");
e.printStackTrace();
}
}
return returnString;
}
Run Code Online (Sandbox Code Playgroud)
玩得开心:)
| 归档时间: |
|
| 查看次数: |
42332 次 |
| 最近记录: |