安卓BuildConfig与DEBUG模式

在安卓项目中Mobule的build.gradle文件中buildConfigField和manifestPlaceholders都可以定义常量,
我们今天说的BuildConfig就是用buildConfigField定义的常量。如下所示:
android {
    compileSdkVersion LIBRARY_COMPILE_SDK_VERSION
    buildToolsVersion LIBRARY_BUILD_TOOLS_VERSION

    defaultConfig {
        applicationId "。。。"
        minSdkVersion LIBRARY_MIN_SDK_VERSION
        targetSdkVersion LIBRARY_TARGET_SDK_VERSION // 不使用api23的动态权限策略(因为xutils)
        versionCode 87
        versionName "5.1.0"
        multiDexEnabled true // 分dex
        manifestPlaceholders = [
        ]
        buildConfigField("String", "VERSION_TIME", "\""+new Date().format("yyyy.MM.dd")+"\"")

用buildConfigField定义的常量会生成在工程的BuildConfig中,然后我们就发现了一些常用的比如:

DEBUG APPLICATION_ID FLAVOR VERSION_CODE VERSION_NAME等等
public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String APPLICATION_ID = "com.irenshi.personneltreasure";
  public static final String BUILD_TYPE = "debug";
  public static final String FLAVOR = "baidu";
  public static final int VERSION_CODE = 87;
  public static final String VERSION_NAME = "5.1.0";
  // Fields from default config.
  public static final String VERSION_TIME = "2018.11.27";
}

那我们如何在代码中使用这些常量呢?看下面这个例子:

public class LogUtil {
    public static void i(String message){
        if(BuildConfig.DEBUG){
            Log.i(generateTag(), message);
        }
    }
    public static void i(String tag,String message){
        if(BuildConfig.DEBUG){
            Log.i(tag, message);
        }
    }
    private static String generateTag() {
        StackTraceElement sElements = new Throwable().getStackTrace()[2];
        String className = sElements.getFileName();
        String methodName = sElements.getMethodName();
        int lineNumber = sElements.getLineNumber();
        return String.format("%s:%s(%s:%d)", className, methodName,className, lineNumber);
    }
}

如果是dubug包输出log信息,如果是release也就是线上版本,我们屏蔽掉log输入。

当然这些常量的应用不只这些,比如我们有时候要确认包的版本VERSION_NAME,

有时候我们会比较版本新旧VERSION_CODE,

有时候我们要获取APPLICATION_ID,

有时候不同的应用商店不同包,也就是我们常说的渠道FLAVOR,

这里还有一个我们自定义的VERSION_TIME,打包的时间。

这样是不是方便管理多了呢。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值