Gradle:如何在 android-library 中使用 BuildConfig,并在应用程序中设置一个标志 [英] Gradle : how to use BuildConfig in an android-library with a flag that gets set in an app
问题描述
我的基于(gradle 1.10 和 gradle plugin 0.8)的 android 项目包含一个大型 android-library,它是 3 个不同 android-apps 的依赖项
My (gradle 1.10 and gradle plugin 0.8)-based android project consists of a big android-library that is a dependency for 3 different android-apps
在我的库中,我希望能够使用这样的结构
In my library, I would love to be able to use a structure like this
if (BuildConfig.SOME_FLAG) {
callToBigLibraries()
}
proguard 将能够根据 SOME_FLAG 的最终值减小生成的 apk 的大小
as proguard would be able to reduce the size of the produced apk, based on the final value of SOME_FLAG
但我不知道如何使用 gradle 作为:
But I can't figure how to do it with gradle as :
* the BuildConfig produced by the library doesn't have the same package name than the app
* I have to import the BuildConfig with the library package in the library
* The apk of an apps includes the BuildConfig with the package of the app but not the one with the package of the library.
我尝试使用 BuildTypes 之类的东西,但没有成功
I tried without success to play with BuildTypes and stuff like
release {
// packageNameSuffix "library"
buildConfigField "boolean", "SOME_FLAG", "true"
}
debug {
//packageNameSuffix "library"
buildConfigField "boolean", "SOME_FLAG", "true"
}
为我的库和我的应用构建共享 BuildConfig 的正确方法是什么?
What is the right way to builds a shared BuildConfig for my library and my apps whose flags will be overridden at build in the apps?
推荐答案
你不能做你想做的,因为 BuildConfig.SOME_FLAG
不会被正确地传播到你的库;构建类型本身不会传播到库——它们总是作为 RELEASE 构建的.这是错误 https://code.google.com/p/android/issues/detail?id=52962
You can't do what you want, because BuildConfig.SOME_FLAG
isn't going to get propagated properly to your library; build types themselves aren't propagated to libraries -- they're always built as RELEASE. This is bug https://code.google.com/p/android/issues/detail?id=52962
要解决这个问题:如果您可以控制所有库模块,则可以确保 callToBigLibraries()
涉及的所有代码都在您可以干净利落的类和包中使用 ProGuard,然后使用反射,以便在它们存在时访问它们,如果它们不存在则优雅地降级.您本质上是在做同样的事情,但您是在运行时而不是编译时进行检查,这有点困难.
To work around it: if you have control over all of the library modules, you could make sure that all the code touched by callToBigLibraries()
is in classes and packages that you can cleave off cleanly with ProGuard, then use reflection so that you can access them if they exist and degrade gracefully if they don't. You're essentially doing the same thing, but you're making the check at runtime instead of compile time, and it's a little harder.
如果您不知道如何执行此操作,请告诉我;如果您需要,我可以提供样品.
Let me know if you're having trouble figuring out how to do this; I could provide a sample if you need it.
这篇关于Gradle:如何在 android-library 中使用 BuildConfig,并在应用程序中设置一个标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!