问题
Im fairly new to Gradle and have been using Eclipse and Ant to do all the builds. Within our app we have a config.properties file located in the assets folder at the same level as src and res etc. In this file we have the following:
developmentsettings=true
defaultLogLevel=4
prodEnvironment=false
How can I replace the values of these 3 variables in the build.gradle file? Do I create a new task for this, and if so, is this within the android tag or not?
Any and all help would be must appreciated
回答1:
I'm not sure if you specifically need these in a separate file... but if not, BuildConfig seems like the way to go. You do something like this in your gradle file:
buildTypes {
debug {
buildConfigField "boolean" "DEVELOPMENT_SETTINGS" "true"
buildConfigField "int" "DEFAULT_LOG_LEVEL" "4"
buildConfigField "boolean" "PROD_ENVIRONMENT" "false"
}
release {
buildConfigField "boolean" "DEVELOPMENT_SETTINGS" "false"
buildConfigField "int" "DEFAULT_LOG_LEVEL" "4"
buildConfigField "boolean" "PROD_ENVIRONMENT" "true"
}
}
And then from your source android code, you reference these fields like so:
BuildConfig.DEVELOPMENT_SETTINGS
BuildConfig.DEFAULT_LOG_LEVEL
BuildConfig.PROD_ENVIRONMENT
You're essentially declaring constants, from gradle, that can be used in your java code.
回答2:
At build.gradle set the following
android {
buildTypes {
debug{
resValue "string", "app_name", "My App Name Debug"
}
release {
resValue "string", "app_name", "My App Name"
}
}
}
You can access them in the usual way with @string/app_name
or R.string.app_name
回答3:
You can let the build system include different versions of the assets/config.properties file depending on whether you're doing a debug or release build. To do this, don't put the file in src/main/res/assets/config.properties; instead, put the debug version in src/debug/res/assets/config.properties and the release version in src/release/res/assets/config.properties. The build system will pick the right version when it does the corresponding build.
来源:https://stackoverflow.com/questions/28739131/android-studio-gradle-how-to-replace-variables-in-a-file