天天看點

Android:Java代碼實作APP普通安裝解除安裝和靜默安裝解除安裝

兩者差異

  • 執行普通安裝、解除安裝,将會彈出确認安裝、解除安裝的提示框,與在檔案管理器中打開APK檔案實作安裝、解除安裝相同。
  • 執行靜默安裝、解除安裝,正常狀态下,前台無任何反應,APP在背景完成安裝和解除安裝。該功能一般也被稱為“背景安裝”,實作該功能需要ROOT。

普通安裝

核心代碼:

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 = -;
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 = -;
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

這四個方法。