TL;DR:根据传递给 gradle 的参数,改变我的来源的干净方法是什么?
我正在构建一个依赖于库 A
的 Android 应用程序.我希望能够支持 A
的多个版本(假设我想同时支持 v1
和 v2
)。我的意思是我希望能够同时构建 myapp-withAv1.apk
和 myapp-withAv2.apk
.
我发现在编译时很容易选择 A
的版本。我想要(例如,我可以在我的 build.gradle
文件中的变量中引用此版本,然后使用 ./gradlew -PversionOfA=v1 build
启动构建)。
但另一个困难是 A
可以更改其公共(public) API,因此我需要根据我正在构建的版本更改我的代码。如果我在做 C++ 或 C#(感谢 #ifdef
)会很容易,但如果没有太多代码重复,我无法找到一种方法,如果你能指出我的方法,我会很高兴实现它。
(请注意,尝试用 if(version == v1)
之类的东西隔离代码分支是行不通的,因为它会导致代码分支调用不可用的 A
方法,因此构建会失败)
最佳答案
我遇到了类似的问题,答案是 productFlavors
在 android 或 sourceSets
对于一个通用的 jar 。基本上,您需要为每个源集中的接口(interface)指定一个实现。
# define the interface in the main
/src/main/java/com/me/IMyInterface.java
# create a v1 and v2 sourceset with the implementation, note paths are the same
/src/v1/java/com/me/MyImplementation.java
/src/v2/java/com/me/MyImplementation.java
现在在你的 gradle 中定义 productFlavors
android {
productFlavors {
v1 {
buildConfigField 'string', 'FLAVOR', 'v1'
}
v2 {
buildConfigField 'string', 'FLAVOR', 'v2'
}
}
//...
}
现在,当您引用实现时,您将获得
sourceSet
对于定义为产品 flavor 名称的版本。// since the package is the same we are unaware of which we are calling
// now we can treat them as the same regardless of the underlying
// implementation differences between v1/v2
import com.me.MyImplementation;
public String doSomethingWithImplementation() {
MyImplementation impl = new MyImplementation();
// here if we are executing in the productFlavor v1
// apk we get the code from the v1 folder, same for v2 apk
return impl.doSomething()
}
关于android - 根据构建参数更改我的源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52724843/