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 = -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这四个方法。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值