Common code for different android flavors

后端 未结 2 1370
感情败类
感情败类 2020-12-07 08:29

I am building 4 different flavors of my Android app.

I have a class Customization.java that is the same for 3 of them and different for 1.

Since

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 09:00

    I use this to override codes for 5 years, just add a piece of code to your build.gradle.

    For lastest gradle plugin(>=3.4.0):

    android {
        ......
        applicationVariants.configureEach { ApplicationVariant variant ->
            AndroidSourceSet flavorSourceSet = android.sourceSets.findByName(variant.productFlavors[0].name);
            if (flavorSourceSet != null) {
                String flavorPath = flavorSourceSet.java.srcDirs[0].path;
                variant.javaCompileProvider.configure { task ->
                    task.exclude { FileTreeElement elem ->
                        !elem.isDirectory() && !elem.file.parent.startsWith(flavorPath) &&
                            new File(flavorPath, elem.path).exists();
                }
            }
        }
    }
    

    For older gradle plugin:

    android {
        ......
        applicationVariants.all { ApplicationVariant variant ->
            AndroidSourceSet flavorSourceSet = android.sourceSets.findByName(variant.productFlavors[0].name);
            if (flavorSourceSet != null) {
                variant.javaCompiler.doFirst {
                    String flavorPath = flavorSourceSet.java.srcDirs[0].path;
                    variant.javaCompiler.exclude { FileTreeElement elem ->
                        !elem.isDirectory() && !elem.file.parent.startsWith(flavorPath) &&
                                new File(flavorPath, elem.path).exists();
                    }
                }
            }
        }
    

    It'll find duplicate classes in the Main sourceset and then exclude it during compile to avoid class duplicate error.

提交回复
热议问题