美文网首页
Android静默安装并重启APP

Android静默安装并重启APP

作者: FynnJason | 来源:发表于2021-02-23 15:38 被阅读0次

    一、在AndroidManifest.xml添加权限

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

    二、在AndroidManifest.xml设置程序安装在内存中

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="xxx.xxx.xxx"
        android:installLocation="internalOnly">
        ···
    </manifest>
    

    三、下载安装包,执行安装和重启命令

    // 安装命令
    val installCommand ="LD_LIBRARY_PATH=/vendor/lib*:/system/lib* pm install -r " +"下载后安装包文件的路径,例如:\sd\download\file.apk"
    // 重启命令
    val restartCommand ="LD_LIBRARY_PATH=/vendor/lib*:/system/lib* am start -n " + packageName + "/" + "启动页的类名称,例如:SplashActivity::class.java.canonicalName"
    // 数组
    val commands = arrayOf(installCommand, restartCommand)
    // 执行命令
    val commandResult = ShellUtils.execCmd(commands, true, true)
    

    四、监听安装包替换的广播

    public class BootBroadcastReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("android.intent.action.PACKAGE_REPLACED")) {
                String packageName = intent.getData().getSchemeSpecificPart();
                if (context.getPackageName().equals(packageName)) {
                    // 获取默认启动activity
                    Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
                    launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(launchIntent);
                }
            }
        }
    }
    

    五、注册第四步的广播

            <receiver android:name=".broadcast.BootBroadcastReceiver">
                <intent-filter>
                    <action android:name="android.intent.action.PACKAGE_ADDED" />
                    <action android:name="android.intent.action.PACKAGE_REPLACED" />
                    <action android:name="android.intent.action.PACKAGE_REMOVED" />
    
                    <data android:scheme="package" />
                </intent-filter>
            </receiver> 
    

    相关文章

      网友评论

          本文标题:Android静默安装并重启APP

          本文链接:https://www.haomeiwen.com/subject/pjgrfltx.html