問題描述
我正在開發一個通過 REST API 與服務器交互的 Android 應用程序.顯然,我需要使用不同的 URL 進行開發和發布構建.注釋和取消注釋代碼非常繁瑣且容易出錯.
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 文件中使用不同的構建類型是一種可以自動化該過程的方法,但我不確定這是否是正確的方法.
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.
構建類型的數量也有可能增加,即.測試、內部發布等.
There is also a possibility of increase in number of build types viz. test, internal-release etc.
推薦答案
如果您使用的是 Android Studio,請使用 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"'
}
}
在這里,我有三種構建類型:標準的 debug
和 release
,以及自定義的 mezzanine
一種.每個都在 BuildConfig
上定義了一個 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
.該字段的值取決于您用于構建該特定應用版本的構建類型.
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.
這篇關于Android:管理不同的服務器 URL 以進行開發和發布的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!