方式一:
Runtime.getRuntime().exec(cmd);
方式二:
先是放入一个String数组,空格用,号代替,将cmd填入.涉及到静默安装的,这里需要root权限
String[] args = {"pm", "install", "-t", "-r", apkPath, "--user", "0"};
exeCmdArgs(args);
// 执行
private static void exeCmdArgs(String[] args)
throws Exception {
ByteArrayOutputStream errorBuffer = new ByteArrayOutputStream();
ByteArrayOutputStream resultBuffer = new ByteArrayOutputStream();
ProcessBuilder processBuilder = null;
Process process = null;
InputStream errorInput = null;
InputStream resultInput = null;
int byteOfRead = 0;
byte[] buffer = new byte[1024];
try {
processBuilder = new ProcessBuilder(args);
process = processBuilder.start();
errorInput = process.getErrorStream();
while (-1 != (byteOfRead = errorInput.read(buffer))) {
errorBuffer.write(buffer, 0, byteOfRead);
}
resultInput = process.getInputStream();
while (-1 != (byteOfRead = resultInput.read(buffer))) {
resultBuffer.write(buffer, 0, byteOfRead);
}
String error = errorBuffer.toString("UTF-8");
String result = resultBuffer.toString("UTF-8");
System.out.println(error);
System.out.println(result);
} finally {
// 关闭
close(errorInput, resultInput);
destroy(process);
}
}