如何使用 android 中的选项执行 unix 'top' 命令

How to execute unix 'top' command with options in android

我正在尝试使用以下运行正常的代码执行 'top' 命令:

try {


        Process proc = Runtime.getRuntime().exec("top");

        InputStream is = proc.getInputStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 500);
        StringBuilder output = new StringBuilder();
        String line = "";
        int count = 0;
        while ((line = reader.readLine()) != null) {
            if(line.trim().equals(""))
                continue;
            if (line.trim().startsWith("User")) {
                count++;
                if (count > 2)
                    break; //'top' command keeps repeating call to itself. we need to stop after 1 call
            }
            if (line.contains("PID")) {
                mainInfo.append(output.toString());
                output.delete(0,output.length());
                continue;
            }


            output.append(line)
                    .append(CPUInfoUtil.SEPARATOR_LINE); //append this separator to help parsing

        }
        reader.close();
        proc.destroy();
        return output.toString();
    } catch (FileNotFoundException e) {

        return null;
    } catch (IOException e) {

        throw new RuntimeException(e);

    }

这将向我返回所有进程,包括 kernel/root 个进程。我只想获取除 woner=root 之外的系统进程。为此,我尝试使用以下选项跟随 'top',但没有用:

Process proc = Runtime.getRuntime().exec(new String[]{"top","U","!root"});

我知道我也可以使用以下代码获得 运行 个进程,但它不提供 'top' 提供的额外信息(例如 Cpu%、线程计数等):

((ActivityManager) act.getSystemService(Context.ACTIVITY_SERVICE)).getRunningServices(Integer.MAX_VALUE);

在做了很多功课后,我开始工作了!以下方式 'top' 可以与多个选项一起使用:

String[] cmd = {"sh","-c",
                "top -m 100 -n 1"
               };
Process proc = Runtime.getRuntime().exec(cmd);

我使用了 -m 和 -n 选项并且效果很好。有关整个选项列表,请参阅手册: 'top' options

我正在使用

Process psProc = Runtime.getRuntime().exec("top -n 1 -d 5");

获取所有进程 运行,然后计算 android 个应用的 CPU 使用情况。