I want to get the overall CPU usage on Android, similar to what Windows' Task Manager does. I can parse the output of the top
program included in Android, but if there is a API call that does the same thing, it would be better.
Any pointers?
On your device, go to Settings and tap Developer Options. In the Monitoring section, select Profile GPU Rendering or Profile HWUI rendering, depending on the version of Android running on the device. In the Profile GPU Rendering dialog, choose On screen as bars to overlay the graphs on the screen of your device.
ATTENTION: This answer is old and does NOT work on newer versions of Android due to enhanced security mechanisms.
For complete CPU usage (not for each process) you can use:
/** * * @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; }
Have fun with it :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With