Wal*_*udi 6 android modularization android-buildconfig
我目前正在致力于模块化我的应用程序,因此我将每个功能放入库模块中。在我的一项功能中,我访问版本代码和名称。但是,尽管我在特定于该模块的 build.gradle 文件中定义了它们
它们不存在于生成的 BuildConfig 文件中
我无法引用原始:app模块的 BuildConfig 文件,因为我不能让我的功能模块依赖于该模块。
是否有其他方法可以从库模块访问此信息?
版本代码和版本名称是应用程序包的属性,库模块不支持它们。
在运行时,您可以传入Context
并借助 来访问该应用程序包元数据PackageManager
。示例:在运行时检测我的应用程序自己的 android:versionCode
虽然上面的答案是好的,但在我看来,这不是最好的方法。一般来说,您希望版本名称和代码存储在 build.gradle 文件之外的某个位置。我们经常这样做,这样我们就可以轻松地从应用程序外部访问它,或者自动更新 CI 系统等。
一个非常简单的示例:您可以将它们放入 gradle.properties 文件中,如下所示:
<!-- add to the end of the file: -->
VERSION_NAME=0.0.1
VERSION_CODE=1
Run Code Online (Sandbox Code Playgroud)
然后,您可以通过属性对象在任何 build.gradle 中简单地访问它们,并将它们添加到 BuildConfig 中,如下所示(注意:它们只有在成功构建后才可用):
// build.gradle file of the chosen module
def versionName = properties["VERSION_NAME"]
def versionCode = properties["VERSION_CODE"]
buildTypes.all {
buildConfigField "String", "VERSION_NAME", "\"$versionName\"" // Escaping quote marks to convert property to String
buildConfigField "int", "VERSION_CODE", "$versionCode"
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以将它们放入专用的 version.properties 文件中。然后你可以这样做:
def versionProps = loadPropertiesFile(project.file('version.properties'))
buildTypes.all {
buildConfigField "String", "VERSION_NAME", getPropEscaped("VERSION_NAME", versionProps)
buildConfigField "int", "VERSION_CODE", getProp("VERSION_CODE", versionProps)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4074 次 |
最近记录: |