Android Apk静默安装卸载的方法(后台安装)

一、大概说下思路

(1)利用系统应用的权限执行pm install命令的安装方法,如果你是大众应用(说的就是通用软件任何Android手机上都用的比如:微信)的话这个方法不现实也是满足不了你的需求的,这个主要在行业终端上使用的。

(2)具体代码如下:

public static boolean installApp(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","com.example.ddd", "-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());
        Toast.makeText(ctx,+errorMsg.toString()+"  "+successMsg , Toast.LENGTH_LONG).show();
        //如果含有“success”单词则认为安装成功
        return successMsg.toString().equalsIgnoreCase("success");
    }

上面的代码是通用的也是网上遍地都能找得到的代码,我就不具体解释了,我主要说下命令

process = new ProcessBuilder("pm", "install","-i","com.example.ddd", "-r", apkPath).start();

android 7.0之前的版本上执行

new ProcessBuilder("pm", "install", "-r", apkPath) 不需要带包名就可以执行成功

Android 7.0之后的系统上执行上述命令会执行失败的,具体的异常我就不贴出来要执行如下的命令:

new ProcessBuilder("pm", "install","-i","com.example.ddd", "-r", apkPath) 这里的包名是你应用程序的包名,而不是安装应用的包名,比如你的这个指令在com.example.ddd这个应用上执行那么你就要写这个应用的包名

然后添加权限:

<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.DELETE_PACKAGES" />

再添加共享进程的配置;

android:sharedUserId="android.uid.system"

接下来就要用系统签名打包安装上去就可以测试了。

系统签名的方法:

@echo off
java -cp signApk.jar SignApk platform.x509.pem platform.pk8 DDD.apk   test.apk
adb install -r test.apk
pause

以上脚本保存到txt里后缀名修改成.bat 然后修改DDD.apk的路径执行即可,DDD是需要签名的apk  test是系统签名后的apk

具体的签名文件文件:

说完了静默安装的方法,接下来也说下静默卸载的方法:

Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent sender = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
PackageInstaller mPackageInstaller = MainActivity.this.getPackageManager().getPackageInstaller();
mPackageInstaller.uninstall("要卸载的应用包名", sender.getIntentSender());// 卸载APK
发布了184 篇原创文章 · 获赞 70 · 访问量 37万+

猜你喜欢

转载自blog.csdn.net/qq_31939617/article/details/102894009
今日推荐