How to get CPU usage statistics on Android?

Randy Sugianto 'Yuku' picture Randy Sugianto 'Yuku' · Mar 18, 2010 · Viewed 44.1k times · Source

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?

Answer

Fabian Knapp picture Fabian Knapp · Apr 22, 2012

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