使用Gradle生成BuildeConfig以及文字资源

BuildConfig

从sdk tools 17开始,构建工具会自动生成BuildeConfig类,默认的长这个样子

public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String APPLICATION_ID = "com.example.ty.testapplication";
  public static final String BUILD_TYPE = "debug";
  public static final String FLAVOR = "";
  public static final int VERSION_CODE = 1;
  public static final String VERSION_NAME = "1.0";
}

这个类我们可以用来自动在Release版本关闭某些功能。比如日志,只需要判断DEBUG变量即可。我们可以通过gradle来为这个类增加成员变量。

android {
    buildTypes {
        debug {
            buildConfigField "String", "API_URL",
            "\"http://test.example.com/api\""
            buildConfigField "boolean", "LOG_HTTP_CALLS", "true"
        }
        release {
            buildConfigField "String", "API_URL",
            "\"http://example.com/api\""
            buildConfigField "boolean", "LOG_HTTP_CALLS", "false"
        }
    }
}

这里我们增加了一个Field,API_URL值就是下面那个地址,注意字符串两个转义的引号是不能少的。
这里我们就生成了新的BuildConfig

public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String APPLICATION_ID = "com.example.ty.testapplication";
  public static final String BUILD_TYPE = "debug";
  public static final String FLAVOR = "";
  public static final int VERSION_CODE = 1;
  public static final String VERSION_NAME = "1.0";
  // Fields from build type: debug
  public static final String API_URL = "http://test.example.com/api";
  public static final boolean LOG_HTTP_CALLS = true;
}

resValue

gradle同样可以用来生成资源文件,比如生成一个字符串资源。

buildTypes {
    debug {
        resValue "string", "app_name", "Example DEBUG"
    }
    release {
        resValue "string", "app_name", "Example"
    }
}

这里生成的字符串在资源文件里无法找到,但是代码里可以引用。比如debug和release的app名字,可以通过这种方式直接修改,是不是特别方便。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值