Java代碼實現APP普通安裝卸載和靜默安裝卸載

來源:互聯網
上載者:User

標籤:安裝   卸載   靜默安裝   靜默卸載   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的包名。

更多內容可參考該頁面內的installuninstallsilentInstallsilentUninstall這四個方法。

Java代碼實現APP普通安裝卸載和靜默安裝卸載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.