Android gradle: Sharing dependencies between product flavors

前端 未结 2 1203
别那么骄傲
别那么骄傲 2021-01-14 23:47

I have 3 product flavors (flavor1, flavor2, flavor3) in my app. flavor1 and flavor2 share some of the dependencies related to ads.

Is there a way to bundle the ad r

相关标签:
2条回答
  • 2021-01-15 00:13

    Solution for sharing dependencies between flavors (updated for implementation which has now replaced compile):

    Since implementation, flavor1Implementation, flavor2Implementation, etc. are all in fact themselves Configurations you can actually apply an inheritance relationship between these steps in the build process.

    Therefore in this case you can specify your shared dependencies, and dependencies for flavor1 only:

    dependencies {
        implementation 'dependency1'
        implementation 'dependency2'
    
        flavor1Implementation 'dependency3'
        flavor1Implementation 'dependency4'
        flavor1Implementation 'dependency5'
    }
    

    ...And then simply allow flavor2Implementation to inherit from flavor1Implementation:

    configurations.flavor2Implementation.extendsFrom(flavor1Implementation)
    

    This can also be used to define more complex relationships between flavors, and multiple inheritance is supported, e.g:

    configurations {
        flavor3Implementation.extendsFrom(
                flavor1Implementation,
                flavor2Implementation
        )
    }
    

    (Finally, just a note that sharing code between flavors should be continued to be handled with sourceSets as per the original question.)

    0 讨论(0)
  • 2021-01-15 00:19

    This is what we did to share directories between flavors:

    sourceSets {
        main {
          java.srcDirs = ['src/main/java']
          res.srcDirs = ['src/main/res']
          assets.srcDirs = ['src/main/assets']
        }
        production {
          java.srcDirs = ['src/main/java', 'src/shared/java']
          res.srcDirs = ['src/main/res', 'src/shared/res']
          assets.srcDirs = ['src/main/assets', 'src/shared/assets']
        }
        logger {
          java.srcDirs = ['src/main/java', 'src/shared/java', 'src/mock/java']
          res.srcDirs = ['src/main/res', 'src/shared/res']
          assets.srcDirs = ['src/main/assets', 'src/shared/assets']
        }
        nowav {
          java.srcDirs = ['src/main/java', 'src/nowav/java', 'src/mock/java']
          res.srcDirs = ['src/main/res', 'src/nowav/res']
          assets.srcDirs = ['src/main/assets', 'src/nowav/assets']
        }
    }
    
    0 讨论(0)
提交回复
热议问题