Android Gradle配置Debug和Release参数的方法
使用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 = "cn.appblog.example";
public static final String BUILD_TYPE = "release";
public static final String FLAVOR = "";
public static final int VERSION_CODE = 1;
public static final String VERSION_NAME = "1.0.0";
// 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的语法
<meta-data
android:name="Logs.enable"
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("yezhou", "Logs.enable = " + enable);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/19/android-gradle-config-debug-and-release-parameters-methods/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。
共有 0 条评论