Đối với việc sử dụng CPU đầy đủ (không phải cho mỗi quá trình), bạn có thể sử dụng:
/**
*
* @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;
}
Hãy vui vẻ với nó :)
Nguồn
2012-04-22 16:14:20
Không sử dụng CPU hay thông tin thời gian có thể được tìm thấy có (hoặc tôi đã bỏ lỡ nó?), chỉ sử dụng bộ nhớ trong số những thứ khác. – yuku
để sử dụng CPU, bạn có thể tham khảo CPUGauge.cpp, tôi nghĩ rằng không có "API công cộng" cho các loại thông tin mà bạn muốn. Hoặc bạn phải tự phân tích cú pháp "/ proc/stat". –
Để tham khảo, đây là nguồn của CPUGauge https://android.googlesource.com/platform/frameworks/native/+/a6938ba/libs/surfaceflinger/CPUGauge.cpp –