在安卓项目中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,打包的时间。
这样是不是方便管理多了呢。