美文网首页Android 组件化、插件化
程序员自我修养之组件化、插件化

程序员自我修养之组件化、插件化

作者: 巴菲伟 | 来源:发表于2021-03-29 11:21 被阅读0次

    一、组件化和集成化的区别

    二者区别

    三、插件化常见手段

        占位式:需要借助临时对象去替换,是为了使用宿主的环境,开发困难

        Hook式:开发相比于占位式简单,且不需要this当前运行宿主环境,插件越多,内存中newElements也就越大

    LoadedApk :通过控制ClassLoader方式,来控制类的加载从而解决:插件越多,内存中newElements也就越大

    四、插件化常见获得当前对象的方法

        方法一:

        Class<?> mPluginActivityClass = getClassLoader().loadClass(activityInfo);

        Constructor constructor = mPluginActivityClass.getConstructor(new Class[]{});

        Object mPluginActivity = constructor.newInstance(new Object[]{});

        //以下两种方式不一定可以拿到,需要去调试

        方法二:

        mPluginActivityClass.newInstance()

        方法三:

        activityThreadClass.getDeclaredConstructor().newInstance();

    五、获取未安装app的类并且启动该类: 

    通过PackageManager—>packageInfo-->activityInfo,可以拿到对应的类的名字

    //1.获取想加载类的.class

    File file =new File(Environment.getExternalStorageDirectory() + File.separator +"p.apk");

    String path = file.getAbsolutePath(); //apk存储目录

    PackageManager manager = getPackageManager();

    PackageInfo packageInfo =

        manager.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES);

    ActivityInfo activityInfo = packageInfo.activities[0];

    //2.下面是拿到当前Activity的实例对象

    Class<?> mPluginActivityClass = getClassLoader().loadClass(activityInfo);

    Constructor constructor = mPluginActivityClass.getConstructor(new Class[]{});

    Object mPluginActivity = constructor.newInstance(new Object[]{});

    ActivityInterface activityInterface = (ActivityInterface) mPluginActivity;

    六、获取未安装app的类并且加载该类:

    通过ClassLoader—>DexPathList——>Element数组,找到对象ClassLoader classLoader = context.getClassLoader();

    //1.拿到DexPathList的对象

    Class baseClassLoader = Class.forName("dalvik.system.BaseDexClassLoader");

    Field pathListFidle = baseClassLoader.getDeclaredField("pathList");

    pathListFidle.setAccessible(true);

    Object dexPathList = pathListFidle.get(classLoader);

    //2.拿到element的对象

    Class clazz = Class.forName("dalvik.system.DexPathList");

    Field dexElement = clazz.getDeclaredField("dexElements");

    dexElement.setAccessible(true);

    Object[] hostElements = (Object[]) dexElement.get(dexPathList);

    //3.dexPath是apk的安装路径

    ClassLoader pluginClassLoader =

        new DexClassLoader(dexPath, context.getCacheDir().getAbsolutePath(),

            null, classLoader);

    Object pluginDexPathList = pathListFidle.get(pluginClassLoader);

    Object[]pluginElements = (Object[]) dexElement.get(pluginDexPathList);

    七、LoadedAPK去加载未安装APP的类

    相关文章

      网友评论

        本文标题:程序员自我修养之组件化、插件化

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