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

1.前言

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

2. 静默安装和卸载

对于APK的安卓和卸载,须要具有系统权限,所以须要在AndroidManifest.xml中配置web

android:sharedUserId="android.uid.system"

可是若是加入该属性后,编译后的APK直接安装就会报以下错误app

INSTALL_FAILED_SHARED_USER_INCOMPATIBLE

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

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
    }