Android gradle 库工程多版本编译问题
android application project中对于debug、release类型不同的编译配置可以通过buildConfig文件实现分离,代码如下:
debug {
buildConfigField "String", "SUFFIX", "\"123\""
}
release {
buildConfigField "String", "SUFFIX", "\"\""
}
但对于android library project(子module),目前的gradle plugin并不支持debug、release这样的编译类型,如果还是按照如上配置,默认release产生效果,debug被忽略。
android gradle文档是这样说的:
For the rest, libraries behave the same as application projects. They have build types and product flavors, and can potentially generate more than one version of the aar.
Note that most of the configuration of the Build Type do not apply to library projects. However you can use the custom sourceSet to change the content of the library depending on whether it’s used by a project or being tested.
而且这个问题在issue tracker上至少存在了两年之久,按照某PM的回复说需要gradle和android gradle plugin配合升级才可以,但现在依然看不到升级的迹象。
详见:https://code.google.com/p/android/issues/detail?id=52962
解决方案:
1、子module通过反射将主module中的BuildConfig的配置项获取到,再进行额外的配置。
public static Object getBuildConfigValue(Context context, String fieldName) {
try {
Class<?> clazz = Class.forName(context.getPackageName()+".BuildConfig");
Field field = clazz.getField(fieldName);
return field.get(null);
} catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
2、isssue tracker上提供的那个dependency配置分离,子module上添加不同的productFlavor,然后配置不同的代码项,主module上根据不同的buildType依赖不同的子module的productFlavor。
⚠ 第一种方法,如果配置了不同的applicationId,请将context.getPackageName()更改main的packageName。