Android 執行命令並獲取命令pid
執行命令如下:
try {
ProcessBuilder builder = new ProcessBuilder(exe);
builder.directory(new File("/system/xbin/"));
builder.redirectErrorStream(true);
process = builder.start();
InputStream in = process.getInputStream();
byte[] re = new byte[1024];
while (in.read(re) != -1) {
String result = new String(re);
publishProgress(result);
}
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
獲取pid:
public static int getProcessId(Process process) {
String str = process.toString();
try {
int i = str.indexOf("=") + 1;
int j = str.indexOf("]");
str = str.substring(i, j);
return Integer.parseInt(str);
} catch (Exception e) {
return 0;
}
}
Kill pid:
public static void kill(Process process) {
int pid = getProcessId(process);
if (pid != 0) {
try {
android.os.Process.killProcess(pid);
} catch (Exception e) {
try {
process.destroy();
} catch (Exception ex) {
//ex.printStackTrace();
}
}
}
}