Android—java实现apk的静默安装、普通安装

  • 执行静默安装,正常状态下,前台无任何反应,APP在后台完成安装。该功能一般也被称为“后台安装”,实现该功能需要ROOT
  • 执行普通安装,将会弹出确认安装的提示框,与在文件管理器中打开APK文件实现安装

静默安装

private void silentInstall(final String path) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                DataOutputStream out = null;
                BufferedReader errorStream = null;
                try {
                    //申请su权限
                    Process process = Runtime.getRuntime().exec("su");
                    out = new DataOutputStream(process.getOutputStream());
                    //执行pm install 命令
                    String command = "pm install -r " + path + "\n";
                    out.write(command.getBytes(Charset.forName("UTF-8")));
                    out.flush();
                    out.writeBytes("exit\n");
                    out.flush();
                    process.waitFor();
                    errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                    String msg = "";
                    String line;
                    while ((line = errorStream.readLine()) != null) {
                        msg += line;
                    }
                    Log.i(TAG, "SilentInstall: "+msg);
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                } finally {
                    try {
                        if (out != null) {
                            out.close();
                        }
                        if (errorStream != null) {
                            errorStream.close();
                        }
                    } catch (IOException e) {
                        Log.e(TAG, e.getMessage(), e);
                    }
                }
            }
        }).start();
    }

普通安装

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
    Uri.fromFile(new File(apkPath)), 
    "application/vnd.android.package-archive"
);
context.startActivity(intent);
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值