方法一:使用BuildConfig类修改参数值
Gradle Android自带BuildConfig配置类,在build工程的时候,可以在build/generated/source/buildConfig下的debug和release路径下找到。
BuildConfig.java类可以在工程中引用;
BuildConfig.java自带DEBUG参数,在打包debug版本的时候,DEBUG = true,在打包release版本的时候,DEBUG=false;
如何自定义BuildConfig参数呢?使用buildConfigField进行配置:
buildTypes {
debug {
buildConfigField "String", "CustomValue",'"buildType"'
buildConfigField "boolean","LOG_DEBUG","true"
}
release {
buildConfigField "String", "CustomValue",'"releaseType"'
buildConfigField "boolean","LOG_DEBUG","false"
}
}
注:buildConfigField 配置格式为: "type","name","value" 形式,如果参数是String类型,"value"外部需加单引号申明内部是String类型的,或者使用转移符 \ ,如:
"\"buildType\""
这样在build 工程的时候, 生成的BuildConfig.java中就包含了这些参数:
public final class BuildConfig {
public static final boolean DEBUG = false;
public static final String APPLICATION_ID = "com.xxx.xxxx";
public static final String BUILD_TYPE = "release";
public static final String FLAVOR = "";
public static final int VERSION_CODE = 1002;
public static final String VERSION_NAME = "1002";
// Fields from build type: release
public static final String CustomValue = "releaseType";
}
最后,在代码中赋值:
/** 是否开发模式 */
private static final boolean isDebug = BuildConfig.DEBUG;
方法二:使用AndroidManifest.xml中的meta-data
在AndroidManifest.xml中申明meta-data参数,注意value的语法
android:value="${LogEnable}"/>
然后在gradle中配置buildTypes;
buildTypes {
debug {
manifestPlaceholders = [LogEnable : true]
}
release {
manifestPlaceholders = [LogEnable : false]
}
}
最后在工程代码中加载meta-data的数据
ApplicationInfo appInfo = null;
try {
appInfo = this.getPackageManager()
.getApplicationInfo(getPackageName(),
PackageManager.GET_META_DATA);
boolean enable=appInfo.metaData.getBoolean("Logs.enable");
Log.d("MyApplication","Logs.enable = "+enable);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}