Android静默安装和卸载APK的代码实现

1.前言

   在实际的终端设备开发中,为保证设备的正常运行,通常会同时运行两个APK,一个用于客户端交互的主APK,另一个是用于监护主APK的辅助APK。
   在市面上常见的安卓APK中,为保证该设备能正常运行通常会集成腾讯的Bugly用于系统的维护和升级,但对于有些APK由于运行环境或使用场景限制,无法使用该第三方功能,就需要我们通过辅助的APK实现对该APK的维护和升级。本文主要讲述通过辅助APK实现对主APK的静默安装和卸载。

2. 静默安装和卸载

对于APK的安卓和卸载,需要具备系统权限,因此需要在AndroidManifest.xml中配置

android:sharedUserId="android.uid.system"

但是如果加入该属性后,编译后的APK直接安装就会报如下错误

INSTALL_FAILED_SHARED_USER_INCOMPATIBLE

显示使用系统权限需要采用系统签名,具体系统签名的实现可参考Android 系统签名实现的三种方式。

2.1 静默安装的实现

private   boolean installApp(String packageName,String apkPath) {
        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder errorMsg = new StringBuilder();
        try {
            process = new ProcessBuilder("pm", "install", "-i", packageName, "-r", apkPath).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) {

        } finally {
            try {
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (Exception e) {

            }
            if (process != null) {
                process.destroy();
            }
        }
        Log.e("result", "" + errorMsg.toString());
        //如果含有“success”认为安装成功
        return successMsg.toString().equalsIgnoreCase("success");
    }

2.2 静默卸载

private void uninstall(String packageName) {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent sender = PendingIntent.getActivity(MyApplication.mContext, 0, intent, 0);
        PackageInstaller mPackageInstaller = MyApplication.mContext.getPackageManager().getPackageInstaller();
        mPackageInstaller.uninstall(packageName, sender.getIntentSender());// 卸载APK
    }

你可能感兴趣的:(Android,Framework)