有人知道如何在运行时访问我的build.gradle文件中的内容吗?
buildscript {
ext {
exoplayerVersion = "2.8.2"
}
}
我想在运行时获取该2.8.2值,但是我不知道该怎么做。感谢您的帮助。
答案 0 :(得分:1)
您可以使用buildConfigField
。
样本声明(摘自官方文档):
android {
...
buildTypes {
release {
// These values are defined only for the release build, which
// is typically used for full builds and continuous builds.
buildConfigField("String", "BUILD_TIME", "\"${minutesSinceEpoch}\"")
resValue("string", "build_time", "${minutesSinceEpoch}")
...
}
debug {
// Use static values for incremental builds to ensure that
// resource files and BuildConfig aren't rebuilt with each run.
// If they were dynamic, they would prevent certain benefits of
// Instant Run as well as Gradle UP-TO-DATE checks.
buildConfigField("String", "BUILD_TIME", "\"0\"")
resValue("string", "build_time", "0")
}
}
}
...
用法:
...
Log.i(TAG, BuildConfig.BUILD_TIME);
更新:
您无法使用Java代码访问ext
属性。只是为了完整答案,您可以在项目的其他gradle文件中使用这些属性。
答案 1 :(得分:0)
@Yashasvi提供的答案是正确的,但是,如果您的用例如您所描述的那样(在代码中获取库的版本),我首先建议研究一下库的API,看看是否有关于版本在那里。例如,Build.VERSION.SDK_INT
为我们提供了Android版本。如果不是,这里是针对您特定问题的更量身定制的答案:
android {
...
buildTypes {
release {
...
buildConfigField("String", "exoplayerVersion", exoplayerVersion)
}
debug {
...
buildConfigField("String", "exoplayerVersion", exoplayerVersion)
}
}
}
然后您可以像这样在BuildConfig文件中找到对该字符串的引用(此文件会在每次构建时生成,因此请确保在添加字段或对其进行更改后才能编译应用程序以查看更改) :
BuildConfig.exoplayerVersion