Android 靜默安裝的幾種方式
阿新 • • 發佈:2019-01-09
/** * 執行具體的靜默安裝邏輯,需要手機ROOT。 * @param apkPath * 要安裝的apk檔案的路徑 * @return 安裝成功返回true,安裝失敗返回false。 */ public boolean install(String apkPath) { boolean result = false; DataOutputStream dataOutputStream = null; BufferedReader errorStream = null; try { // 申請su許可權 Process process = Runtime.getRuntime().exec("su"); dataOutputStream = new DataOutputStream(process.getOutputStream()); // 執行pm install命令 String command = "pm install -r " + apkPath + "\n"; dataOutputStream.write(command.getBytes(Charset.forName("utf-8"))); dataOutputStream.flush(); dataOutputStream.writeBytes("exit\n"); dataOutputStream.flush();process.waitFor(); errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream())); String msg = ""; String line; // 讀取命令的執行結果 while ((line = errorStream.readLine()) != null) { msg += line; } Log.d("TAG", "install msg is " + msg); // 如果執行結果中包含Failure字樣就認為是安裝失敗,否則就認為安裝成功if (!msg.contains("Failure")) { result = true; } } catch (Exception e) { Log.e("TAG", e.getMessage(), e); } finally { try { if (dataOutputStream != null) { dataOutputStream.close(); } if (errorStream != null) { errorStream.close(); } } catch (IOException e) { Log.e("TAG", e.getMessage(), e); } } return result; }