您的位置:首页 > 移动开发 > Android开发

通过ddmlib杀死某个android进程的方法

2012-10-26 14:38 288 查看
首先获取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}'`";

本文出自 “忆往昔。。。” 博客,请务必保留此出处http://memory.blog.51cto.com/6054201/1037994
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: