Android-執行命令列指令碼
阿新 • • 發佈:2018-12-14
方式一:
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); } }