Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get CPU usage statistics on Android?

Tags:

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?

like image 953
Randy Sugianto 'Yuku' Avatar asked Mar 18 '10 04:03

Randy Sugianto 'Yuku'


People also ask

How do I check my CPU and GPU usage on Android?

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.


Video Answer


1 Answers

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 :)

like image 178
Fabian Knapp Avatar answered Nov 12 '22 22:11

Fabian Knapp