從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 }
