Android:管理不同的服务器 URL 以进行开发和发布 [英] Android: Managing different server URL for development and release

查看:8
本文介绍了Android:管理不同的服务器 URL 以进行开发和发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个通过 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"'
        }
    }

在这里,我有三种构建类型:标准的 debugrelease,以及自定义的 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 以进行开发和发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆