tmho tmho - 1 month ago 10
Android Question

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 gradle build, it builds the release.apk to point to http://example.com and the debug.apk to point to http://debug.example.com.

I have achieved this using the following:

buildTypes {
debug {
buildConfig "public final static String API_HOST = \"http://debug.example.com\";"
}

release {
buildConfig "public final static String API_HOST = \"https://example.com\";"
}
}


However that seems pretty dirty

Cheers

Answer

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
    }
}