gpt4 book ai didi

android-gradle-plugin - Gradle : how to use BuildConfig in an android-library with a flag that gets set in an app

转载 作者:行者123 更新时间:2023-12-03 01:34:47 26 4
gpt4 key购买 nike

我的基于(gradle 1.10 和 gradle 插件 0.8)的 android 项目包含一个大型 android 库,它依赖于 3 个不同的 android 应用程序

在我的图书馆中,我希望能够使用这样的结构

if (BuildConfig.SOME_FLAG) {
callToBigLibraries()
}

因为 proguard 能够根据 SOME_FLAG 的最终值减小生成的 apk 的大小

但我不知道如何使用 gradle 来做到这一点:

* the BuildConfig produced by the library doesn't have the same package name than the app
* I have to import the BuildConfig with the library package in the library
* The apk of an apps includes the BuildConfig with the package of the app but not the one with the package of the library.

我尝试使用 BuildTypes 和类似的东西,但没有成功

release {
// packageNameSuffix "library"
buildConfigField "boolean", "SOME_FLAG", "true"
}
debug {
//packageNameSuffix "library"
buildConfigField "boolean", "SOME_FLAG", "true"
}

为我的库和应用程序构建共享 BuildConfig 的正确方法是什么?其标志将在应用程序中的构建时被覆盖?

最佳答案

作为解决方法,您可以使用此方法,该方法使用反射从应用程序(而不是库)获取字段值:

/**
* Gets a field from the project's BuildConfig. This is useful when, for example, flavors
* are used at the project level to set custom fields.
* @param context Used to find the correct file
* @param fieldName The name of the field-to-access
* @return The value of the field, or {@code null} if the field is not found.
*/
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 e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}

例如,要获取 DEBUG 字段,只需从您的 Activity 中调用此字段即可:

boolean debug = (Boolean) getBuildConfigValue(this, "DEBUG");

我还在 AOSP Issue Tracker 上分享了这个解决方案.

关于android-gradle-plugin - Gradle : how to use BuildConfig in an android-library with a flag that gets set in an app,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21365928/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com