Android支持Split Apks后,如何获得指定包名下的所有类

从Android5.0以后,支持多个apk动态部署,这导致以前通过单一apk获取包路径下的所有类的方法失效,不过稍微修改一下原先的代码就可以,代码如下

 1 public static final List<Class<?>> getClassesFromPackage(Context ctx, String pkgName) {
 2         List<Class<?>> rtnList = new ArrayList<Class<?>>();
 3         String[] apkPaths = ctx.getApplicationInfo().splitSourceDirs;// 获得所有的APK的路径
 4         DexFile dexfile = null;
 5         Enumeration<String> entries = null;
 6         String name = null;
 7         for (String apkPath : apkPaths) {
 8             try {
 9                 dexfile = new DexFile(apkPath);// 获得编译后的dex文件
10                 entries = dexfile.entries();// 获得编译后的dex文件中的所有class
11                 while (entries.hasMoreElements()) {
12                     name = (String) entries.nextElement();
13                     if (name.startsWith(pkgName)) {// 判断类的包名是否符合
14                         rtnList.add(Class.forName(name));
15                     }
16                 }
17             } catch (ClassNotFoundException | IOException e) {
18             } finally {
19                 try {
20                     if (dexfile != null) {
21                         dexfile.close();
22                     }
23                 } catch (IOException e) {
24                 }
25             }
26         }
27         return rtnList;
28     }

 

posted @ 2019-03-24 20:55  铭久  阅读(2336)  评论(1编辑  收藏  举报