这里展示两种方法,以top命令为例,需要注意的是top命令返回的结果只包含当前用户id对应的进程相关的process信息。
在adb shell直接执行命令获取的是以root进行的,所以可以查看所有进程。
public void execShellCommand(int tmp) {
try {
String prop = SystemProperties.get("sys.top.debug");
StringBuilder mStringResult = new StringBuilder();
// 查询某一个进程的信息
List<String> cmds = new ArrayList<>();
if (prop != null && prop.length() > 0) {
Collections.addAll(cmds, prop.split(" "));
} else {
cmds.add("top");
cmds.add("-b");
cmds.add("-m");//10 tasks to show
cmds.add("10");
cmds.add("-n");//Exit after 1 iteration
cmds.add("1");
cmds.add("-H");
cmds.add("-s");
cmds.add("4");
cmds.add("-o");
cmds.add("pid,tid,user,%cpu,virt,res,name");
}
ProcessBuilder pb = new ProcessBuilder(cmds);
Process p = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null){
mStringResult.append(line).append("\n");
}
mResultList.add(mStringResult.toString());
mHandler.sendEmptyMessage(0);
Iterator i = cmds.iterator();
StringBuilder s = new StringBuilder();
while (i.hasNext()) {
s.append(i.next());
}
Log.d(TAG,"CMDS : " + s.toString());
Log.d(TAG,"results : " + mStringResult.toString());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (Exception ex){
ex.printStackTrace();
Log.e(TAG,"Exception : " + ex.toString());
}
}
public void execShellCommand() {
Process p = null;
String cmd = SystemProperties.get("sys.top.debug");
StringBuilder mStringResult = new StringBuilder();
if (cmd == null || cmd.length() <= 0) {
cmd = "top -b -m 10 -n 1 -H -s 4 -o pid,tid,user,%cpu,virt,res,name";
}
try {
p = Runtime.getRuntime().exec("su -c " + cmd);
p.waitFor(5, TimeUnit.SECONDS);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null){
mStringResult.append(line).append("\n");
}
mResultList.add(mStringResult.toString());
mHandler.sendEmptyMessage(0);
Log.d(TAG,"CMDS : " + cmd);
Log.d(TAG,"results : " + mStringResult.toString());
} catch (Exception e) {
Log.e(TAG, "// Exception from " + cmd + " : " + e.getMessage());
} finally {
if (p != null) {
p.destroy();
}
}
}