I am using Android Studio and Gradle to build Android applications. I would like to have different strings within the Java code based on which type of build it is (debug vs. release). What is the best way to do this?
For example - I want to have different URLs if I am in debug or release. Also, I want to specify different GUIDs and other keys / strings.
The obvious hacky way to do this is to do a search and replace of a string in AndroidManifest.xml or worse yet, in a Java file. This approach seems error prone and hacky to me - is there a better way to do this?
There are many ways you can do this, although I usually do
android {
buildTypes {
release {
buildConfigField("String", "URL", "your_url_on_release")
}
debug {
buildConfigField("String", "URL", "your_url_on_debug")
}
}
}
You then can access them on your java code by using:
BuildConfig.URL
You can test this using Android Studio Build Variants, by changing your application variant to debug or release ( e.g. http://prntscr.com/8waxkw)
You have many solutions to do this, here's a simple case:
buildTypes {
debug { ... }
release { ... }
}
productFlavors {
staging { ... }
production { ... }
}
build types are for build management proguarding, debugging, signing, etc.
productFlavors are for all app internal configuration.
If you want to add resources related to the flavours you can create and add to src/(flavor_name)/res/values/ folder your urls.xml config file.
With this, in android studio, you'll directly see, all the builds variants in the corresponding window and the right urls.xml file associated to the current context and leave the gradle config clean.
Of course, this method works also for any resource you would need in your app.
For more detail, you can read this : http://developer.android.com/tools/building/configuring-gradle.html#workBuildVariants
I would do it with product flavors as explained in this post.
Related
To make development faster, I want to do the following:
android {
defaultConfig {
resConfigs "en"
}
}
My app has a lot of languages, and doing this saves significant time while developing. However, I do NOT want to release a version with this set. Unfortunately, resConfigs is not available on product flavors or build types, so I can't set it in debug {}, for example.
How can I automatically exclude resConfigs from release variants? I do not want to have to remember comment out that line of code when I'm building for release.
Wouldn't this work?
Detect the debug build, reset the configurations and add your desired debug configuration.
applicationVariants.all { variant ->
if (variant.buildType.name == "debug") {
variant.mergedFlavor.resourceConfigurations.clear()
variant.mergedFlavor.resourceConfigurations.add("en")
}
}
My solution was inspired by this answer to a related question. Here's how you do it:
in app/build.gradle
// Reset `resConfigs` for release
afterEvaluate {
android.applicationVariants.all { variant ->
if (variant.buildType.name.equals('release')) {
variant.mergedFlavor.#mResourceConfiguration = null
}
}
}
This works because mResourceConfiguration is the backing field for resConfigs. Unfortunately, The Android Gradle DSL does not currently expose a method to reset resConfigs, so we're forced to access the field directly using the groovy #<fieldName> syntax. This works, even though mResourceConfiguration is private.
WARNING: this solution is a little fragile, as the Android Gradle build tools team could change the name of that field at any time, since it is not part of the public API.
I have been using gradle for creating different build variants for different companies for an Android app.
For example I have build flavors:
Company1
Company2
And then I have build types:
Production
Preview
Development
So this will create 6 build variants:
Company1Production
Company1Preview
Company1Development
Company2Production
Company2Preview
Company2Development
So the question is:
Actually I don't need the development build type for company 2, I only need it for company 1.
Is there a way I can specify only company 1 have the development build type?
I have a lot of companies in my projects, some of the build type just don't make sense for those companies, and it confuses people who want to build the app.
To answer my own question, I have found the documentation on the Gradle Plugin User Guide
Filtering Variants
When you add dimensions and flavors, you can end up with variants that don't make sense. For example you may define a flavor that uses your Web API and a flavor that uses hard-coded fake data, for faster testing. The second flavor is only useful for development, but not in release builds. You can remove this variant using the variantFilter closure, like this:
android {
productFlavors {
realData
fakeData
}
variantFilter { variant ->
def names = variant.flavors*.name
if (names.contains("fakeData") && variant.buildType.name == "release") {
variant.ignore = true
}
}
}
With the configuration above, your project will have only three variants:
realDataDebug
realDataRelease
fakeDataDebug
You can't stop the Android plugin from creating the matrix of all builds, but you can cause the build to fail if it's not valid. For example, if you don't want Flavor2 Debug builds to work, you can stop them like this:
afterEvaluate {
tasks['prepareFlavor2DebugDependencies'].doFirst {
throw new IllegalArgumentException("This project is not valid")
}
}
I am developing an Android application that interacts with server via REST APIs. Obviously I need to use different URL for development and release builds. Commenting and un-commenting code is very tedious and error pron.
Which is the best way to handle this situation? Using different build types in gradle file is one which could automate the process, but I am not sure if this is the right way to go.
There is also a possibility of increase in number of build types viz. test, internal-release etc.
If you are using Android Studio, use buildConfigField to add custom fields to your BuildConfig class.
buildTypes {
debug {
buildConfigField "String", "SERVER_URL", '"http://test.this-is-so-fake.com"'
}
release {
buildConfigField "String", "SERVER_URL", '"http://prod.this-is-so-fake.com"'
}
mezzanine.initWith(buildTypes.release)
mezzanine {
buildConfigField "String", "SERVER_URL", '"http://stage.this-is-so-fake.com"'
}
}
Here, I have three build types: the standard debug and release, plus a custom mezzanine one. Each defines a SERVER_URL field on BuildConfig.
Then, in Java code, you just refer to BuildConfig.SERVER_URL. That field will have a value based on what build type you used to build that particular edition of the app.
It can be managed by using ProductFlavours in app build.gradle. ProductFlavours will manage different URL ie. development and release.
Please have a look it on medium.
It involves detailed explanation.
I had a similar issue and I solved it using
if (BuildConfig.DEBUG) { }
You will need to import
import com.commandsoftware.androidbookingapp.BuildConfig;
I had a similar problem with writing to logcat. I wanted to write all the messages if the app was signed with the debug key, otherwise write almost none of them. I solved the problem with this line of code:
boolean showAllMessages = ((getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0);
then using that boolean in my log writer. You should be able to do something similar when you initialize the URIs.
I am using Eclipse. I can't say with certainty that this will work in other IDE environments. This answer implies that it might be an Eclipse-only feature
Hey I am trying to statically define String values that change according to the configuration I am running. So if I run a test configuration, it uses the test API url, but if I run a regular build, it statically sets the real API URL.
I am using two strings files right now, one in the main folder and one in the androidTest folder in Android Studio. This works well for getting different Strings per configuration, but I'de like to do it statically rather than dealing with Resource fetches.
Is this possible?
I have seen this answer for ANT, but I am not sure how to do it with Gradle.
You can generate gradle constants like this:
build.gradle
android {
buildTypes {
debug {
buildConfigField "String", "FOO", "\"foo\""
}
release {
buildConfigField "String", "FOO", "\"bar\""
}
}
}
And access them in your code through BuildConfig.FOO
Note you may need to clean and/or restart your IDE for the to come in to effect.
I want to override some strings in my res/strings.xml with gradle.
I know that since Android Gradle Plugin 0.7.+ theres the possibilty to have a variant specific source folder.
But my app has a lot of flavors and I don't want to add additionally variant specific folders.
UPDATE 2014-01-17
What I want in detail:
I have some variables in my Resources that are depending only by the buildType (e.g. "release").
First I thought my SOLUTION_1 (override data after resources were merged) is nice, because if I have to change these variables I just have to change them in the build.config (just one place).
But as Scott Barta wrote in the comment below there are some good reasons why this solution is NOT a good idea.
So i tried another solution SOLUTION_2 (just merge the right resources) based on this GitHub project of shakalaca. I think this way is more elegant and I still have the advantage just to change the variables in one place!
SOLUTION_1 (override data after resources were merged):
What I did in AS 0.4.2:
in build.gradle I try to override the string "Hello World" to "OVERRIDE" (based on my answer at this post):
android.applicationVariants.all{ variant ->
// override data in resource after merge task
variant.processResources.doLast {
overrideDataInResources(variant)
}
}
def overrideDataInResources(buildVariant){
copy {
// *** SET COPY PATHS ***
try {
from("${buildDir}/res/all/${buildVariant.dirName}") {
// println "... FROM: ${buildDir}/res/all/${buildVariant.dirName}"
include "values/values.xml"
}
} catch (e) {
println "... EXCEPTION: " + e
}
into("${buildDir}/res/all/${buildVariant.dirName}/values")
// println "... INTO: ${buildDir}/res/all/${buildVariant.dirName}/values"
// --- override string "hello_world"
filter {
String line ->
line.replaceAll("<string name=\"hello_world\">Hello world!</string>",
"<string name=\"hello_world\">OVERRIDE</string>");
}
// *** SET PATH TO NEW RES ***
buildVariant.processResources.resDir = file("${buildDir}/res/all/${buildVariant.dirName}/values/values/values.xml")
// println "... NEW RES PATH: " + "${buildDir}/res/all/${buildVariant.dirName}/values/values/values.xml"
}
}
The copy and filter task works fine, but I couldn't set the "new" values.xml as string resource.
SOLUTION_2 (just merge the right resources)
define a floavor for specific buildType (e.g. "releaseRes")
merge this resourses with the flavor you want to build:
android.applicationVariants.all{ variant ->
variant.mergeResources.doFirst{
checkResourceFolder(variant)
}
}
def checkResourceFolder(variant){
def name = variant.name;
if(name.contains("Release")){
android.sourceSets.release.res.srcDirs = ['src/releaseRes/res']
android.sourceSets.flavor1.res.srcDirs = ['src/flavor1/res']
}
}
You should strive to come up with a solution that doesn't involve writing any custom code in your build files, especially code that does tricky things with reassigning source sets on the fly. Custom Gradle code is a little funky to write, and it's difficult to debug and maintain. The new build system is extremely powerful and already has tons of flexibility, and it's likely that you can already do what you want; it's just a matter of learning how.
Especially if you're just learning the ins and outs of Android-Gradle projects (and it's so new that we all are), it's best to try hard to work with the functionality built into the system before thinking outside the box.
Some recommendations:
It's unlikely you need to vary resources based on build type. A build type in Android-Gradle is supposed to be something like debug or release, where the difference is in debuggability, compiler optimization, or signing; build types are supposed to be functionally equivalent to each other. If you look at the properties you can set on a build type through the Groovy DSL, you can see the intent: debuggable, jniDebugBuild, renderscriptDebugBuild, renderscriptOptimLevel, packageNameSuffix, versionNameSuffix, signingConfig, zipAlign, runProguard, proguardFile, proguardFiles.
If you still think you want to vary resources based on build type, there's already an easy way to do that with the current build system. You can have a build-type-specific resource directory, put your resources in there, and the resource merging in the build system will take care of things for you at build time. This is one of the powerful features in Android/Gradle. See Using Build Flavors - Structuring source folders and build.gradle correctly for information on how to make that work.
If you want to vary something based on build type and your needs are very quick and simple, you might want to do the switch in Java code instead of resources and instead of in the build system. There's the BuildConfig mechanism for that sort of thing -- it's a Java class that defines a DEBUG flag based on debug/release build status, and you can add your own custom Java code from different build types to do more meaningful things. BuildConfig was intended for allowing small functional differences between build types, for cases where a debug build might want to perform some wasteful operation to assist in development, like doing more extensive data validation or creating more detailed debug logging, and those wasteful things are best optimized out of release builds. Having said that, it might be an appropriate mechanism to do what you want.
Consider using flavors for what you're using build types for now. Conceptually a flavor is kind of like a build type in that it's another variant of your application that can be built; the build system will create a matrix of flavors vs. build types and can build all combinations. However, flavors address a different use case, where different flavors share most code but can have significant functional differences. A common example is a free vs. paid version of your application. Inasmuch as a different resource in different variants of your app represents different functionality, that might indicate a need for a different flavor. Flavors can have different resource directories that are merged at build time in the same way as build configs; see the question linked above for more info.
I don't believe you need to customize the build script at all to achieve what you want. According to my reading of http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants; when the build runs, resources will be merged from the following folders, if they exist;
src/[flavour][buildType]/res
src/[buildType]/res
src/[flavour]/res
src/main/res
So I believe you can achieve what you want by simply add the resources in src/release/res.
Though you can tweak the folder names by specifying the relevant sourceSets.[type].res.srcDirs if you really want to change them.
If anyone stumble upon this
buildTypes {
debug{
buildConfigField "String", "Your_string_key", '"yourkeyvalue"'
buildConfigField "String", "SOCKET_URL", '"some text"'
buildConfigField "Boolean", "LOG", 'true'
}
release {
buildConfigField "String", "Your_string_key", '"release text"'
buildConfigField "String", "SOCKET_URL", '"release text"'
buildConfigField "Boolean", "LOG", 'false'
}
}
And to access those values using build variants:
if(!BuildConfig.LOG)
// do something with the boolean value
Or
view.setText(BuildConfig.yourkeyvalue);