首先获取ps指令的打印信息:


  
  1. private static String getPsPrint(IDevice device) {
  2. OutputStream os = new ByteArrayOutputStream();
  3. try {
  4. device.executeShellCommand("ps",
  5. new OutputStreamShellOutputReceiver(os));
  6. os.flush();
  7. return os.toString();
  8. } catch (TimeoutException e) {
  9. e.printStackTrace();
  10. } catch (AdbCommandRejectedException e) {
  11. e.printStackTrace();
  12. } catch (IOException e) {
  13. e.printStackTrace();
  14. } catch (ShellCommandUnresponsiveException e) {
  15. e.printStackTrace();
  16. }
  17. return "";
  18. }

其中OutputStreamShellOutputReceiver类:


  
  1. public class OutputStreamShellOutputReceiver implements IShellOutputReceiver {
  2. OutputStream os;
  3. public OutputStreamShellOutputReceiver(OutputStream os) {
  4. this.os = os;
  5. }
  6. public boolean isCancelled() {
  7. return false;
  8. }
  9. public void flush() {
  10. }
  11. public void addOutput(byte[] buf, int off, int len) {
  12. try {
  13. os.write(buf,off,len);
  14. } catch(IOException ex) {
  15. throw new RuntimeException(ex);
  16. }
  17. }
  18. }

获得ps的打印信息之后,需要根据进程名分析出pid:


  
  1. public static String parsePid(IDevice device, String exeName) {
  2. String content = getPsPrint(device);
  3. String[] pidInfos = content.split("\n");
  4. for (String info : pidInfos) {
  5. if (info != null) {
  6. // shell 18867 18856 852 300 c022c0bc afe0cdec S ./gsnap
  7. if (info.contains(exeName)) {
  8. String[] fragments = info.split(" ");
  9. int idx = 0;
  10. for (String str : fragments) {
  11. if ((str != null) && (!str.trim().equals(""))) {
  12. idx++;
  13. }
  14. if (idx == 2) {
  15. return str;
  16. }
  17. }
  18. }
  19. }
  20. }
  21. return "";
  22. }

最后,根据得到的pid,杀掉此android进程:


  
  1. public static void killProcess(IDevice device, String pid) {
  2. // 旧的手机,缺乏grep和awk程序!
  3. //String killCmd = "kill -9 `ps | grep \"gsnap\" | grep -v \"grep\" | awk '{print $2}'`";
  4. String killCmd = "kill -9 " + pid;
  5. try {
  6. device.executeShellCommand(killCmd,
  7. new OutputStreamShellOutputReceiver(System.out));
  8. } catch (TimeoutException e) {
  9. e.printStackTrace();
  10. } catch (AdbCommandRejectedException e) {
  11. e.printStackTrace();
  12. } catch (IOException e) {
  13. e.printStackTrace();
  14. } catch (ShellCommandUnresponsiveException e) {
  15. e.printStackTrace();
  16. }
  17. }

之所以会这么复杂,是因为这个:

  1. // 旧的手机,缺乏grep和awk程序!
  2. //String killCmd = "kill -9 `ps | grep \"gsnap\" | grep -v \"grep\" | awk '{print $2}'`";