
正文
Android支持Split Apks后,如何获得指定包名下的所有类
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
从Android5.0以后,支持多个apk动态部署,这导致以前通过单一apk获取包路径下的所有类的方法失效,不过稍微修改一下原先的代码就可以,代码如下
public static final List<Class<?>> getClassesFromPackage(Context ctx, String pkgName) {
List<Class<?>> rtnList = new ArrayList<Class<?>>();
String[] apkPaths = ctx.getApplicationInfo().splitSourceDirs;// 获得所有的APK的路径
DexFile dexfile = null;
Enumeration<String> entries = null;
String name = null;
for (String apkPath : apkPaths) {
try {
dexfile = new DexFile(apkPath);// 获得编译后的dex文件
entries = dexfile.entries();// 获得编译后的dex文件中的所有class
while (entries.hasMoreElements()) {
name = (String) entries.nextElement();
if (name.startsWith(pkgName)) {// 判断类的包名是否符合
rtnList.add(Class.forName(name));
}
}
} catch (ClassNotFoundException | IOException e) {
} finally {
try {
if (dexfile != null) {
dexfile.close();
}
} catch (IOException e) {
}
}
}
return rtnList;
}








