我有一个具有多种风格的 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
...
}}
Run Code Online (Sandbox Code Playgroud)
defaultConfig {
buildConfigField "boolean", "USE_THE_CRAZY_LIB", "false"
}
Run Code Online (Sandbox Code Playgroud)
productFlavors {
crazyFlavor {
buildConfigField "boolean", "USE_THE_CRAZY_LIB", "true"
//... all the other things in this flavor
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
(有关该方法的更多信息,例如此处)
对于其他口味(在src/otherFlavor/java):
public class FlavorController {
public static void init(){
}
}
Run Code Online (Sandbox Code Playgroud)适合您的口味(中src/crazyFlavor/java):
public class FlavorController {
public static void init(){
SomeLibrary.init();
}
}
Run Code Online (Sandbox Code Playgroud)在你的Application:
public class MainApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
FlavorController.init();
}
}
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
2195 次 |
| 最近记录: |