Android apk静默安装完成后自启动

1.apk静默安装的代码

 public boolean silentInstall(Context context, String filePath) {
        File file = new File(filePath);
        PackageManager packageManager = context.getPackageManager();
        Class pmClz = packageManager.getClass();
        try {
            if (Build.VERSION.SDK_INT >= 21) {
                Class aClass = Class.forName("android.app.PackageInstallObserver");
                Constructor constructor = aClass.getDeclaredConstructor();
                constructor.setAccessible(true);
                Object installObserver = constructor.newInstance();
                Method method = pmClz.getDeclaredMethod("installPackage", Uri.class, aClass, int.class, String.class);
                method.setAccessible(true);
                method.invoke(packageManager, Uri.fromFile(file), installObserver, 2, null);
            } else {
                Method method = pmClz.getDeclaredMethod("installPackage",
                        Uri.class, Class.forName("android.content.pm.IPackageInstallObserver"), int.class, String.class);
                method.setAccessible(true);
                method.invoke(packageManager, Uri.fromFile(file), null, 2, null);
            }
            return true;
        } catch (Exception e) {          
            e.printStackTrace();
        }
        return false;
    }

2.apk安装后自启动的前提是:

       安装完成会触发“android.intent.action.PACKAGE_REPLACED”广播,apk覆盖安装后会接收到该广播,初次安装不会触发。这个广播需要静态注册如下:

        
            
                
                
                
                
            
        

3.需要如下权限

    
    
    
    

4.自己定义的广播接收器

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        String localPkgName = context.getPackageName();
        //取得MyReceiver所在的App的包名
        Uri data = intent.getData();
        String installedPkgName = data.getSchemeSpecificPart();
        //取得安装的Apk的包名,只在该app覆盖安装后自启动
        if ((action.equals(Intent.ACTION_PACKAGE_ADDED) || action.equals(Intent.ACTION_PACKAGE_REPLACED)) && installedPkgName.equals(localPkgName)) {
            /**
             * 启动activity
             */
            Intent mIntent = new Intent( );
            mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName comp = new ComponentName("xxx包名", "xxx启动的activity");
            mIntent.setComponent(comp);
            mIntent.setAction("android.intent.action.VIEW");
            context.startActivity(mIntent);

        }
    }
}

5.参考文档

https://blog.csdn.net/qq_23261197/article/details/86240372

https://blog.csdn.net/mythmayor/article/details/80653621

你可能感兴趣的:(系统)