我有一个有很多口味的Android应用程序,我只想要特定的口味来包含某个代码段。更具体地说,我想使用第三方库并仅以特定的方式添加该库的初始化代码。
public class MainApplication
extends Application {
@Override
public void onCreate() {
super.onCreate();
//The library is only included in the build of specific flavors, so having this code in other flavors will not compile
//I want the following code only to be included in the flavors that include the library
SomeLibrary.init();
//other code that is relevant for all flavors
...
}}
答案 0 :(得分:2)
defaultConfig {
buildConfigField "boolean", "USE_THE_CRAZY_LIB", "false"
}
productFlavors {
crazyFlavor {
buildConfigField "boolean", "USE_THE_CRAZY_LIB", "true"
//... all the other things in this flavor
}
}
然后在Application
public class MainApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
if (BuildConfig.USE_THE_CRAZY_LIB) {
Method method = clazz.getMethod("init", SomeLibrary.class);
Object o = method.invoke(null, args);
}
}
}
(有关该方法的更多信息,例如here)
对于其他风味(src/otherFlavor/java
):
public class FlavorController {
public static void init(){
}
}
为你的风味(src/crazyFlavor/java
):
public class FlavorController {
public static void init(){
SomeLibrary.init();
}
}
在Application
:
public class MainApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
FlavorController.init();
}
}
答案 1 :(得分:0)
您还可以使用gradle通过使用自定义配置来解决此问题。
使用此模式为此行创建自定义配置到build.gradle文件
configurations {
prodFlavBuildTypeCompile
}
dependencies {
prodFlavBuildTypeCompile 'com.google.code.gson:gson:2.8.0'
}
例如,我的应用程序风格是免费和付费,其中构建类型 dev 和 prod
configurations {
freeDevCompile
freeProdCompile
}
dependencies {
freeDevCompile 'com.google.code.gson:gson:2.8.0'
}
在主文件夹中,使用公共代码保留应用程序。
public class BaseApp extends Application {
@Override
public void onCreate() {
super.onCreate();
}
}
并在每种产品口味中使用实施代码。
public class ApplicationImpl extends BaseApp {
@Override
public void onCreate() {
super.onCreate();
SomeLibrary.init();
}
}
其他口味的代码,
public class ApplicationImpl extends BaseApp {
@Override
public void onCreate() {
super.onCreate();
// code for flavour 2
}
}