【发布时间】: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);
【问题讨论】: