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进行配置:

1
2
3
4
5
6
7
8
9
10
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中就包含了这些参数:

1
2
3
4
5
6
7
8
9
10
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";
}

最后,在代码中赋值:

1
2
/** 是否开发模式 */
private static final boolean isDebug = BuildConfig.DEBUG;

使用AndroidManifest.xml中的meta-data

在AndroidManifest.xml中申明meta-data参数,注意value的语法

1
2
3
4
<meta-data
android:name="Logs.enable"
android:value="${LogEnable}"
/>

然后在gradle中配置buildTypes;

1
2
3
4
5
6
7
8
buildTypes {
debug {
manifestPlaceholders = [LogEnable : true]
}
release {
manifestPlaceholders = [LogEnable : false]
}
}

最后在工程代码中加载meta-data的数据

1
2
3
4
5
6
7
8
9
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();
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :