问题描述
我知道我可以使用 debugCompile
只为 debug build
引入 dependency
.是否有一种很好的、简化的方法来执行所需的 代码初始化
?如果没有依赖项,其他变体将无法编译.
I know that I can use debugCompile
to only pull in a dependency
for the debug build
. Is there a good, streamlined way to do the code initialization
that is required as well? Without the dependencies the other variants will fail to compile.
推荐答案
您有几个选择.
选项 1: 为所有构建包含 Stetho(使用 compile
而不是 debugCompile
)并且只在您的 Application 用于调试构建的类.
Option 1: Include Stetho for all builds (using compile
instead of debugCompile
) and only initialize it in your Application
class for debug builds.
这很容易做到.在您的 Application
类中,像这样检查 BuildConfig.DEBUG
:
This is pretty easy to do. In your Application
class, check BuildConfig.DEBUG
like so:
if (BuildConfig.DEBUG) {
Stetho.initialize(
Stetho.newInitializerBuilder(this)
.enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
.enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this))
.build()
);
}
选项 2:仅包含 Stetho 用于调试版本,并为调试版本和发布版本创建不同的 Application
类.
Option 2: Only include Stetho for debug builds, and create different Application
classes for debug and release builds.
多亏了 Gradle,应用程序可以为不同的构建变体提供不同的源集.默认情况下,您具有发布和调试构建类型,因此您可以拥有三种不同的源集:
Thanks to Gradle, applications can have different source sets for different build variants. By default, you have release and debug build types, so you can have three different source sets:
- debug 用于您只需要在调试版本中使用的代码
- release 用于您只需要在发布版本中使用的代码
- main 用于所有构建中所需的代码
- debug for code you only want in debug builds
- release for code you only want in release builds
- main for code you want in all builds
您的应用程序代码目前可能都在 main
源集中.您可以简单地在应用程序中的 main
文件夹旁边创建一个名为 debug
的新文件夹,并为您想要的所有内容镜像 main
文件夹的结构添加用于调试版本.
Your application code is likely all currently in the main
source set. You can simply create a new folder called debug
next to the main
folder in your application and mirror the structure of your main
folder for everything you want to add for debug builds.
在这种情况下,您希望 main
源集中的 Application
类根本不引用 Stetho.
In this case, you want an Application
class in your main
source set that doesn't reference Stetho at all.
然后你需要在你的 debug
源集中有一个 Application
类,它可以像往常一样初始化 Stetho.
Then you want an Application
class in your debug
source set that initializes Stetho like you normally would.
您可以在 Stetho 示例 中看到此设置的示例.具体来说,这里是主要的应用程序class 和 这是调试应用程序类.另请注意,他们在每个源集中设置了清单,用于选择要使用的应用程序类.
You can see an example of this setup in the Stetho sample. Specifically, here's the main Application class, and here's the debug Application class. Also note that they set up manifests in each source set that selects which Application class to use.
这篇关于仅在调试构建变体中包含 Stetho的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!