Reputation: 21247
Does anyone know how to access something that I have in my build.gradle file at runtime?
buildscript {
ext {
exoplayerVersion = "2.8.2"
}
}
I'd like to grab that 2.8.2 value at runtime, but I can't figure out how to do it. Thanks for any help.
Upvotes: 1
Views: 712
Reputation: 5325
You can use buildConfigField
.
Sample declaration (taken from the official docs) :
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")
}
}
}
...
Usage:
...
Log.i(TAG, BuildConfig.BUILD_TIME);
Update:
You can NOT access ext
properties in Java code. Just for completeness of the answer, you can use these properties in other gradle files in your project.
Upvotes: 1
Reputation: 8406
The answer that @Yashasvi provided is correct however if your use case is as you described (getting a version of a library in code) I would first suggest to look into the APIs of the library and see if there is any notion of version in there. That is for example what Build.VERSION.SDK_INT
provide us for android version. if not here is more tailored answer for your specific question:
android {
...
buildTypes {
release {
...
buildConfigField("String", "exoplayerVersion", exoplayerVersion)
}
debug {
...
buildConfigField("String", "exoplayerVersion", exoplayerVersion)
}
}
}
And then you can find a reference to that String in your BuildConfig file like this (this file gets generated on each build so make sure you compile the app after adding the field or making changes to it in order to see the changes):
BuildConfig.exoplayerVersion
Upvotes: 0