【问题标题】:How to execute unix 'top' command with options in android如何在android中使用选项执行unix'top'命令
【发布时间】:2016-09-04 05:07:52
【问题描述】:

我正在尝试使用以下正常工作的代码执行“顶部”命令:

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

    }

这将返回所有进程,包括内核/根进程。我只想获取除 woner=root 之外的系统进程。为此,我尝试使用以下选项跟随“顶部”,但没有成功:

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

我知道我也可以使用以下代码获取正在运行的进程,但它不提供“top”提供的其他信息(例如 Cpu%、线程数等):

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

【问题讨论】:

    标签: android unix command


    【解决方案1】:

    做了很多功课后,我得到了这个工作!以下方式 'top' 可以与尽可能多的选项一起使用:

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

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

    【讨论】:

      【解决方案2】:

      我正在使用

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

      让所有进程运行,然后计算 Android 应用的 CPU 使用率。

      【讨论】:

        猜你喜欢
        • 2016-04-09
        • 2022-01-19
        • 2020-05-17
        • 1970-01-01
        • 2012-10-02
        • 2012-04-29
        • 2011-03-26
        • 1970-01-01
        • 2019-07-03
        相关资源
        最近更新 更多