在Gradle中为Android中的库项目构建变体

Jav*_*aga 22 android gradle library-project android-studio build.gradle

我正在尝试使用Gradle配置一个包含一些外部库的项目.使用Gradle我可以使用Build Variants为主应用程序设置不同的环境配置(在配置文件中有一个类),这样我就可以根据这些变量执行代码.

问题是我如何为图书馆项目做同样的事情?我为这个项目创建了这个库,我想为不同的场景设置不同的Build Variants.

例如:在库中,当在调试模式下运行时,然后打印所有日志,以便我可以在开发时看到它们.在发布模式下不要.

文件结构:

src ----- > debug -> java -> config -> PlayerEnvConfig
            main -> com.mypackagename -> etc...
            release -> java -> config -> PlayerEnvConfig
Run Code Online (Sandbox Code Playgroud)

debug中的代码:package config;

/**
 * Environment configuration for Release
*/
public final class PlayerEnvConfig {
    public static final boolean USE_REPORTING = true;
    public static final boolean USE_ANALYTICS = true;
    public static final boolean USE_LOGGING = false;
    public static final boolean USE_DEBUG_LOGGING = false;
    public static final boolean USE_DEBUGING = false;
}
Run Code Online (Sandbox Code Playgroud)

发布代码:

package config;

/**
 * Environment configuration for Release
*/
public final class PlayerEnvConfig {
    public static final boolean USE_REPORTING = true;
    public static final boolean USE_ANALYTICS = true;
    public static final boolean USE_LOGGING = false;
    public static final boolean USE_DEBUG_LOGGING = false;
    public static final boolean USE_DEBUGING = false;
}
Run Code Online (Sandbox Code Playgroud)

问题是,对于主项目,我可以使用此Build类型为不同场景配置不同的应用程序,但是如何为库项目执行相同操作?

因为目前我在http://tools.android.com/tech-docs/new-build-system/user-guide中读到的内容,库只会在测试时使用调试模式.

有任何想法吗?

谢谢!

Bel*_*loo 14

这是来自谷歌代码问题的@bifmadei答案,它对我有帮助:

尝试在依赖项目中设置它

android {
    publishNonDefault true
    ...
}
Run Code Online (Sandbox Code Playgroud)

这在使用它的项目中

dependencies {
    releaseCompile project(path: ':theotherproject', configuration: 'release')
    debugCompile project(path: ':theotherproject', configuration: 'debug')
}
Run Code Online (Sandbox Code Playgroud)

摘自此处:https://code.google.com/p/android/issues/detail? id = 66805


tbr*_*lle 12

不确定您的配置有什么问题,但有关您的需求,我会采用不同的方式.

在gradle构建文件中,您可以使用buildConfig关键字向BuildConfig.java生成的类添加特定行.

所以你可以添加类似的东西build.gradle:

    release {
        buildConfig "public static final String USE_REPORTING = true;"
    }
    debug {

        buildConfig "public static final String USE_REPORTING = false;"
    }
Run Code Online (Sandbox Code Playgroud)

所以只有一个PlayerEnvConfig

public static final boolean USE_REPORTING = BuildConfig.USE_REPORTING;
Run Code Online (Sandbox Code Playgroud)

甚至不再PlayerEnvConfig使用直接BuildConfig上课.


编辑自更新以来,语法已更改:

buildConfigField "<type>", "<name>", "<value>"
Run Code Online (Sandbox Code Playgroud)

  • 谢谢tbruyelle我尝试过它(这种方式更加智能btw)但问题仍然存在.问题在于,在构建运行应用程序时,库总是以发布模式构建(即使我在Android Studio中选择了调试模式).在我之前发布的链接中解释了这一点.但它是否存在任何解决方法?"调试类型由测试应用程序使用.发布类型由使用库的项目使用." (7认同)