Android 后台静默安装

后台静默安装,就无需写代码调用系统的 PackageInstaller 接口,直接使用指令的方式去执行。
与cmd直接执行 adb install 不同,代码中需要使用 pm 这个系统bin文件

    private void startUpdate() {

        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder errorMsg = new StringBuilder();
        try {
            **// 7.0以后版本需要额外添加
            //           "-i", "当前应用包名", 
            // 两个字段,并且需要应用支持 android.permission.INSTALL_PACKAGES 权限**
            process = new ProcessBuilder("pm", "install", "-i", "当前应用包名", "-r", "sdcard/test.apk").start();
            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String s;
            while ((s = successResult.readLine()) != null) {
                successMsg.append(s);
            }
            while ((s = errorResult.readLine()) != null) {
                errorMsg.append(s);
            }
        } catch (Exception e) {
            Log.e(TAG, "Exception " + e.toString());
        } finally {
            try {
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (Exception e) {

            }
            if (process != null) {
                process.destroy();
            }
        }
        Log.e(TAG, "errorMsg " + errorMsg.toString());
        Log.d(TAG, "successMsg " + successMsg.toString());

    }

你可能感兴趣的:(Android)