与gradle这个和android不同的API主机不同、主机、gradle、android

2023-09-07 08:48:02 作者:逆光之处是暖伤i

我不知道是否有可能利用提供的gradle构建每一个不同的API主机。理想情况下,我想通过我的code相同的访问不断,所以当我做一个构建的gradle,它构建了release.apk指向的 http://example.com 和debug.apk指向 HTTP://debug.example。 COM 。

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\";"
    }
}

不过,这似乎pretty脏

However that seems pretty dirty

干杯

推荐答案

我觉得今天的摇篮拥有一个更好的选择是同时指定 productFlavors buildTypes (下面的例子)。

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

该buildTypes控制我签什么证书,Proguard的是否运行。

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

该productFlavors控制在预期环境,其中包括自定义资源,以及不同的包名,所以我可以并排安装它们两侧。

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.

然后我配置我的服务器地址中的strings.xml对每个变种,并在运行时加载它。

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例如:

strings.xml example from the "dev" variant:

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

的build.gradle片段:

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