我正在尝试使用以下正常工作的代码执行'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);
}
这将返回包括内核/根进程在内的所有进程。我想只获取系统进程,除了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);
答案 0 :(得分:0)
做了很多功课后我就搞定了!以下方式'top'可以与尽可能多的选项一起使用:
String[] cmd = {"sh","-c",
"top -m 100 -n 1"
};
Process proc = Runtime.getRuntime().exec(cmd);
我使用-m和-n选项,它的工作性很好。有关完整的选项列表,请参见手册: 'top' options
答案 1 :(得分:0)
我正在使用
Process psProc = Runtime.getRuntime().exec("top -n 1 -d 5");
让所有进程运行,然后计算Android应用程序的CPU使用率。