首先获取ps指令的打印信息:
- private static String getPsPrint(IDevice device) {
- OutputStream os = new ByteArrayOutputStream();
- try {
- device.executeShellCommand("ps",
- new OutputStreamShellOutputReceiver(os));
- os.flush();
- return os.toString();
- } catch (TimeoutException e) {
- e.printStackTrace();
- } catch (AdbCommandRejectedException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (ShellCommandUnresponsiveException e) {
- e.printStackTrace();
- }
- return "";
- }
其中OutputStreamShellOutputReceiver类:
- public class OutputStreamShellOutputReceiver implements IShellOutputReceiver {
- OutputStream os;
- public OutputStreamShellOutputReceiver(OutputStream os) {
- this.os = os;
- }
- public boolean isCancelled() {
- return false;
- }
- public void flush() {
- }
- public void addOutput(byte[] buf, int off, int len) {
- try {
- os.write(buf,off,len);
- } catch(IOException ex) {
- throw new RuntimeException(ex);
- }
- }
- }
获得ps的打印信息之后,需要根据进程名分析出pid:
- public static String parsePid(IDevice device, String exeName) {
- String content = getPsPrint(device);
- String[] pidInfos = content.split("\n");
- for (String info : pidInfos) {
- if (info != null) {
- // shell 18867 18856 852 300 c022c0bc afe0cdec S ./gsnap
- if (info.contains(exeName)) {
- String[] fragments = info.split(" ");
- int idx = 0;
- for (String str : fragments) {
- if ((str != null) && (!str.trim().equals(""))) {
- idx++;
- }
- if (idx == 2) {
- return str;
- }
- }
- }
- }
- }
- return "";
- }
最后,根据得到的pid,杀掉此android进程:
- public static void killProcess(IDevice device, String pid) {
- // 旧的手机,缺乏grep和awk程序!
- //String killCmd = "kill -9 `ps | grep \"gsnap\" | grep -v \"grep\" | awk '{print $2}'`";
- String killCmd = "kill -9 " + pid;
- try {
- device.executeShellCommand(killCmd,
- new OutputStreamShellOutputReceiver(System.out));
- } catch (TimeoutException e) {
- e.printStackTrace();
- } catch (AdbCommandRejectedException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (ShellCommandUnresponsiveException e) {
- e.printStackTrace();
- }
- }
之所以会这么复杂,是因为这个:
- // 旧的手机,缺乏grep和awk程序!
- //String killCmd = "kill -9 `ps | grep \"gsnap\" | grep -v \"grep\" | awk '{print $2}'`";