2.0 版本的 Android Studio 和 Gradle 中的 DexFile [英] DexFile in 2.0 versions of Android Studio and Gradle

查看:25
本文介绍了2.0 版本的 Android Studio 和 Gradle 中的 DexFile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码来实例化某个包中包含的所有类.

I am using the following code to instantiate all the classes included in a certain package.

DexFile df = new DexFile(getPackageCodePath());
for (Enumeration<String> iter = df.entries(); iter.hasMoreElements(); ) {
    String className = iter.nextElement();
    if (className.contains(packageName) && !className.contains("$")) {
        myClasses.add(Class.forName(className).newInstance());
    }
}

不幸的是,它不再正常工作了.从 Android Studio 2 和 Gradle 2.0.0 开始,DexFile 条目不再包含应用中的所有类,而仅包含属于 com.android.tools 包的类.

Unfortunately it is not working properly anymore. Since Android Studio 2 and Gradle 2.0.0, the DexFile entries no longer include all the classes within the app but only the classes belonging to the com.android.tools package.

这是一个已知问题吗?

推荐答案

看起来这个问题与新的 InstantRun 适用于 Gradle 2.0.0 的 Android 插件中的功能.

Looks like this issue is related to the new InstantRun feature in the Android Plugin for Gradle 2.0.0.

getPackageCodePath() 获取指向 Android 文件系统中 base.apk 文件的字符串.如果我们解压缩该 apk,我们可以在其根文件夹中找到一个或多个 .dex 文件.从方法 df.entries() 获得的条目遍历在该根文件夹中找到的 .dex 文件,以获得其所有已编译的类.

getPackageCodePath() gets a String pointing towards the base.apk file in the Android file system. If we unzip that apk we can find one or several .dex files inside its root folder. The entries obtained from the method df.entries() iterates over the .dex files found in that root folder in order to obtain all of its compiled classes.

但是,如果我们使用新的Android Plugin for Gradle,我们只会找到与android运行时和即时运行相关的.dex(包com.tools.android.fd.runtimecom.tools.android.fd.commoncom.tools.android.tools.ir.api).每隔一个类将被编译成几个 .dex 文件,压缩到一个名为 Instant-run.zip 的文件中,并放入 apk 的根文件夹中.

However, if we are using the new Android Plugin for Gradle, we will only find the .dex related to the android runtime and instant run (packages com.tools.android.fd.runtime, com.tools.android.fd.common and com.tools.android.tools.ir.api). Every other class will be compiled in several .dex files, zipped into a file called instant-run.zip and placed into the root folder of the apk.

这就是问题中发布的代码无法列出应用程序中的所有类的原因.尽管如此,这只会影响调试版本,因为发布版本不具备 InstantRun 功能.

That's why the code posted in the question is not able to list all the classes within the app. Still, this will only affect Debug builds since the Release ones don't feature InstantRun.

这篇关于2.0 版本的 Android Studio 和 Gradle 中的 DexFile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆