如何获得在Android CPU占用率统计? [英] How to get CPU usage statistics on Android?

查看:269
本文介绍了如何获得在Android CPU占用率统计?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得总CPU使用率,在Android上,类似于Windows的任务管理器。我可以解析程序包含在Android的输出,但如果有一个API调用做同样的事情,它会更好。

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.

任何指针?

推荐答案

有关完整的CPU使用情况(而不是针对每个流程),你可以使用:

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

这篇关于如何获得在Android CPU占用率统计?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆