这里使用的是ps命令,不用root或系统权限。
public int getPid(String name) {
String cmd = ("ps | grep " + name);
String str = execRootCmd(cmd);
if (str == null || str == "" || str.length() < 1)
return -1;
else {
String[] arr = str.split("\\s+");
for (String ss : arr) {
boolean result = ss.matches("[0-9]+");
if (result)
return Integer.parseInt(ss);
}
}
return -1;
}
execRootCmd我这里是默认执行了su,而ps是不需要使用到su的,所以没有root权限的童鞋,直接用
Runtime.getRuntime().exec(cmd)
<a href="http://www.sharezer.com/archives/1314">exeRootCmd可以见http://www.sharezer.com/archives/1314</a>