標籤:安裝 卸載 靜默安裝 靜默卸載 app
兩者差異
- 執行普通安裝、卸載,將會彈出確認安裝、卸載的提示框,與在檔案管理工具中開啟APK檔案實現安裝、卸載相同。
- 執行靜默安裝、卸載,正常狀態下,前台無任何反應,APP在後台完成安裝和卸載。該功能一般也被稱為“後台安裝”。
普通安裝
核心代碼:
Intent intent = new Intent(Intent.ACTION_VIEW);intent.setDataAndType( Uri.fromFile(new File(apkPath)), "application/vnd.android.package-archive");context.startActivity(intent);
普通卸載
核心代碼:
Uri packageURI = Uri.parse("package:" + packageName);Intent intent = new Intent(Intent.ACTION_DELETE, packageURI);context.startActivity(intent);
上述代碼中,packageName是目標APP的包名。
靜默安裝
核心代碼:
private static final String SILENT_INSTALL_CMD = "pm install -r ";
String installCmd = SILENT_INSTALL_CMD + apkPath;// PM指令不支援中文int result = -1;DataOutputStream dos = null;Process process = null;try { process = Runtime.getRuntime().exec("su"); dos = new DataOutputStream(process.getOutputStream()); dos.writeBytes(installCmd + "\n"); dos.flush(); dos.writeBytes("exit\n"); dos.flush(); process.waitFor(); result = process.exitValue();} catch (Exception e) { e.printStackTrace();} finally { try { if(dos != null) { dos.close(); } if(process != null){ process.destroy(); } } catch (IOException e) { e.printStackTrace(); }}return result;
靜默卸載
核心代碼:
// 如果要保留資料,需要加-k參數,但是卸載會不完全private static final String SILENT_UNINSTALL_CMD = "pm uninstall ";
String uninstallCmd = SILENT_UNINSTALL_CMD + appPackageName;int result = -1;DataOutputStream dos = null;Process process = null;try { process = Runtime.getRuntime().exec("su"); dos = new DataOutputStream(process.getOutputStream()); dos.writeBytes(uninstallCmd + "\n"); dos.flush(); dos.writeBytes("exit\n"); dos.flush(); process.waitFor(); result = process.exitValue();} catch (Exception e) { e.printStackTrace();} finally { try { if(dos != null) { dos.close(); } if(process != null){ process.destroy(); } } catch (IOException e) { e.printStackTrace(); }}return result;
上述代碼中,appPackageName是目標APP的包名。
更多內容可參考該頁面內的install、uninstall、silentInstall和silentUninstall這四個方法。
Java代碼實現APP普通安裝卸載和靜默安裝卸載