如何在Android上获取CPU使用情况统计信息?

时间:2010-03-18 04:46:50

标签: android cpu-usage processor performance-monitor

我想获得Android上的整体CPU使用率,类似于Windows的任务管理器。我可以解析Android中包含的top程序的输出,但是如果有一个API调用做同样的事情,那就更好了。

任何指针?

3 个答案:

答案 0 :(得分: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;
}

玩得开心:)

答案 1 :(得分:2)

您可以参考“DevTools”项目。

使用ActivityManager可以获得大量信息,例如ActivityManager.RunningAppProcessInfo,ActivityManager.RunningTaskInfo,...

但我不确定结果会与'top'命令相同。

ActivityManager

答案 2 :(得分:0)

您可以阅读/proc/stat并分析文件内容。第一行是这样的:
cpu 79242 0 74306 842486413 756859 6140 67701 0
列的含义如下,从左到右:

 - 1st column : user = normal processes executing in user mode
 - 2nd column : nice = niced processes executing in user mode
 - 3rd column : system = processes executing in kernel mode
 - 4th column : idle = twiddling thumbs
 - 5th column : iowait = waiting for I/O to complete
 - 6th column : irq = servicing interrupts
 - 7th column : softirq = servicing softirqs


平均闲置百分比:
X % = ( idle * 100 ) / ( user + nice + system + idle + iowait + irq + softirq )
您可以计算时间增量与数字CPU使用率之间的空闲差异。