Different API Host with gradle and android

2019-02-20 03:50发布

问题:

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

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


回答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



回答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.