[AS]自定义BuildConfig字段

默认状态下,Android Studio 会自动生成一个 BuildConfig 类,其内部定义了一些静态常量:

public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String APPLICATION_ID = "xxx.xxx.xxx";
  public static final String BUILD_TYPE = "debug";
  public static final String FLAVOR = "";
  public static final int VERSION_CODE = 36;
  public static final String VERSION_NAME = "2.2.36.beta";
}

这个类由编译器动态生成,不允许开发者修改,但也并非完全不能改。

比如想知道APP的编译时间,此时,在这里增加一个字段,借助自动生成机制,写入编译时间,再合适不过了。

使用方法

1、语法:

buildConfigField("TYPE", "NAME", "VALUE")
  • TYPE - 常量类型(常见:String、boolean、int、long等);
  • NAME - 新增的常量名;
  • VALUE - 新增的常量值;
    这3个参数,都必须是“String类型”(编译过程中,会自动将上面参数前后的引号去除,往下看栗子)。

2、举个栗子
定义字段:

buildConfigField("String", "BUILD_STRING", "\"2019.12.28 12:06\"")
buildConfigField("char", "BUILD_CHAR", "'c'")
buildConfigField("long", "BUILD_LONG", "1231231231231231231L")
buildConfigField("int", "BUILD_INT", "1231")
buildConfigField("float", "BUILD_FLOAT", "3.14f")
buildConfigField("double", "BUILD_DOUBLE", "3.14")
buildConfigField("boolean", "BUILD_BOOLEAN", "true")
buildConfigField("short", "BUILD_SHORT", "1")
buildConfigField("int[]", "BUILD_INT_ARRAY", "{1,2,3}")

生成字段:

// Fields from default config.
public static final String BUILD_STRING = "2019.12.28 12:06";
public static final char BUILD_CHAR = 'c';
public static final long BUILD_LONG = 1231231231231231231L;
public static final int BUILD_INT = 1231;
public static final float BUILD_FLOAT = 3.14f;
public static final double BUILD_DOUBLE = 3.14;
public static final boolean BUILD_BOOLEAN = true;
public static final short BUILD_SHORT = 1;
public static final int[] BUILD_INT_ARRAY = {1,2,3};

注意:
第三个参数定义的时候,一定要用引号包起来,而且数据格式一定要符合Java定义(long后加L,float加F,char加单引号,数组有花括号等等)


本文经「原本」原创认证,作者Shawn.XiaFei,访问yuanben.io查询【O9OBWJN7】获取授权信息。

你可能感兴趣的:([AS]自定义BuildConfig字段)