简体   繁体   English

使用gradle自动更改App Environment(开发/生产...)

[英]Use gradle to change App Environment ( development/ production…) automatically

I am developing android application.In the app, I need to have multiple servers such as development, staging and production. 我正在开发android应用程序。在应用程序中,我需要有多个服务器,如开发,登台和生产。 For each environment, I had to specify others sensitive keys as well. 对于每个环境,我还必须指定其他敏感键。 I am changing flag for each environment manually it for now. 我现在手动更改每个环境的标志。 I want to use gradle to automate this. 我想用gradle来自动化这个。 According to gradle documentation , there is a terms called build type such as release and debug by default. 根据gradle文档,默认情况下有一个称为构建类型的术语,例如发布调试 There is also product flavours . 还有产品口味 I am not sure which one to use and how to. 我不确定使用哪一个以及如何使用。 Any advice would be appreciate. 任何建议都会很感激。

This is how i change App env in Application.java 这就是我在Application.java中更改App env的方法

public static final int APP_ENV = 2;//2 => dev, 1 => staging, 0 => production

This is how I differentiate url and other keys 这是我区分网址和其他密钥的方式

switch (envVar){
            case DEV :
                url ="http://a.com";
                google_analytic_id="aaaa..";
                ....
                break;
            case STAG :
                url = "http://b.com";
                google_analytic_id="bbbb..";
                .....
                break;
            case PRO :
                google_analytic_id="cccc..";
                .....
                break;
            default:
                url ="http://a.com";
                break;
        }

You should use flavours for this. 你应该使用味道。 A partial build.gradle file might look like: 部分build.gradle文件可能如下所示:

productFlavors {
  production {
    buildConfigField 'String', 'URL', '"http://a.com"'
  }
  development {
      buildConfigField 'String', 'URL', '"http://b.com"'
  }
}

which will populate BuildConfig.java with the information you provided. 这将使用您提供的信息填充BuildConfig.java Then in your Java code you can do things like: 然后在Java代码中,您可以执行以下操作:

System.out.println("My URL is " + BuildConfig.URL);

And you can create your particular build with: 您可以使用以下命令创建特定的构建:

gradle assembleProductionDebug

or 要么

gradle assembleDevelopmentDebug

(where you can switch Debug for Release as required). (您可以根据需要切换Debug for Release)。

Details of how to use product flavours is available at http://developer.android.com/tools/building/configuring-gradle.html 有关如何使用产品口味的详细信息,请访问http://developer.android.com/tools/building/configuring-gradle.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM