Gradle - 使用口味

Gradle - using flavors

我有一个项目在单个 class 中使用低功耗蓝牙扫描。自 API 21 以来,Android 已弃用我使用的一些方法,并希望我用新方法替换它们。我真的不想切断所有 API 19 岁和 20 岁的人,所以我正在尝试研究 Gradle 口味。

到目前为止我发现,为了创建不同的风格,您需要为包含不同源代码的两种风格提供两个不同的包。

我的问题是:如果我只需要单个 class 中的方差,我是否应该尝试使用 flavor?另外,我应该怎么做呢?我查看了 Gradle 文档,除了如何声明不同的风格之外没有太多内容,而实际设置方面的内容并不多。

我在 flavors

的部分找到了这个

a library is defined with a 'english' and 'french' flavor. When compiling the 'french' variant, a separate macro is defined which leads to a different binary being produced.

但也仅此而已。我将如何实际设置二进制文件和更改?谢谢!

gradle 风味示例:

android {
    ...
    defaultConfig { ... }
    signingConfigs { ... }
    buildTypes { ... }
    productFlavors {
        demo {
            applicationId "com.buildsystemexample.app.demo"
            versionName "1.0-demo"
            buildConfigField 'Boolean', 'isDemo', 'true'
        }
        full {
            applicationId "com.buildsystemexample.app.full"
            versionName "1.0-full"
            buildConfigField 'Boolean', 'isDemo', 'false'
        }
    }
}

您可以为每种构建风格放置不同的源代码。

刚刚阅读此页:https://developer.android.com/tools/building/configuring-gradle.html

您可以使用 flavors 来做到这一点,但由于它只是一个 class 我建议您改为这样做:

首先,制作一个界面:

public interface Something{
    //Put anything that will be common to both classes here.
    public void doSomething();
}

创建两个实现该接口的 classes。一个使用新的和令人兴奋的版本:

public class SomethingWithNewStuff implements Something{
    @Override
    public void doSomething(){
        //Go nuts and use new fancy features where you need them
    }
}

然后覆盖旧版本需要更新的方法:

public class LegacySomething implements Something{
    @Override
    public void doSomething(){
        //do something in a legacy way.
    }
}

然后,当您实例化 class:

Something something;

int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.KITKAT){
    something = new SomethingWithNewStuff();
} else{
    something = new LegacySomething();
}

something.doSomething();

根据您的具体操作,您可以通过多种方式实现同​​一类事情。在某些情况下,让一个 class 扩展另一个可能比让两者都继承自一个公共接口等更好。

无论哪种方式,最终这可能比为一个小改动维护两个单独的构建要少工作。