Skip to content Skip to sidebar Skip to footer

Different Api Host With Gradle And Android

I was wondering if it is possible to provide a different API Host per build using gradle. Ideally I would like to access the constant through my code the same so when I do a gradl

Solution 1:

I think a better alternative with today's Gradle features is to specify both productFlavors and buildTypes (example below).

The buildTypes control what certificate I sign with, and whether Proguard is run.

The productFlavors control the intended environment, which includes custom resources, as well as a different package name so I can install them both side by side.

Then I configure my server address in strings.xml for each variant and load it at runtime.

src/dev/res/values/strings.xml
src/staging/res/values/strings.xml

strings.xml example from the "dev" variant:

<string name="config_url">http://com.example.debug</string>

build.gradle snippet:

productFlavors {
    dev {
        packageName "com.example.dev"
    }

    staging {
        packageName "com.example.staging"
    }
}

buildTypes {
    debug {
        versionNameSuffix " debug"
        signingConfig signingConfigs.debug
    }

    release {
        // A release build runs Proguard, and signs with a release certificate
        zipAlign true
        runProguard true
        proguardFile 'proguard-project.txt'
        proguardFile getDefaultProguardFile('proguard-android-optimize.txt')
        signingConfig signingConfigs.release
    }
}

Solution 2:

An alternative is to use buildConfigField:

buildTypes {
  debug {
    buildConfigField 'String', 'API_HOST', '"https://debug.example.com"'
  }

  release {
    buildConfigField 'String', 'API_HOST', '"https://example.com"'
  }
}

You would then refer to it in your code via BuildConfig.API_HOST

Solution 3:

So I ended up speaking to one of the gradleware engineers about this.... My initial solution is the correct way. Google/Gradle will be improving this in the future.

To add multiple values you separate the the strings with comas.

Post a Comment for "Different Api Host With Gradle And Android"