問題描述
我正在開發(fā)一個(gè)通過 REST API 與服務(wù)器交互的 Android 應(yīng)用程序.顯然,我需要使用不同的 URL 進(jìn)行開發(fā)和發(fā)布構(gòu)建.注釋和取消注釋代碼非常繁瑣且容易出錯(cuò).
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.
處理這種情況的最佳方法是什么?在 gradle 文件中使用不同的構(gòu)建類型是一種可以自動(dòng)化該過程的方法,但我不確定這是否是正確的方法.
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.
構(gòu)建類型的數(shù)量也有可能增加,即.測(cè)試、內(nèi)部發(fā)布等.
There is also a possibility of increase in number of build types viz. test, internal-release etc.
推薦答案
如果您使用的是 Android Studio,請(qǐng)使用 buildConfigField
將自定義字段添加到您的 BuildConfig
類中.
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"'
}
}
在這里,我有三種構(gòu)建類型:標(biāo)準(zhǔn)的 debug
和 release
,以及自定義的 mezzanine
一種.每個(gè)都在 BuildConfig
上定義了一個(gè) SERVER_URL
字段.
Here, I have three build types: the standard debug
and release
, plus a custom mezzanine
one. Each defines a SERVER_URL
field on BuildConfig
.
然后,在 Java 代碼中,您只需引用 BuildConfig.SERVER_URL
.該字段的值取決于您用于構(gòu)建該特定應(yīng)用版本的構(gòu)建類型.
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.
這篇關(guān)于Android:管理不同的服務(wù)器 URL 以進(jìn)行開發(fā)和發(fā)布的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!