Link dependencies for specific flavors with dimens

2019-08-27 22:37发布

问题:

I'm developing an android app which has two types: free and premium. Each tier has 2 versions: lightweight and heavy. Here's the Gradle implenetation of this:

flavorDimensions "tier", "distro"
productFlavors {
    free {
        dimension "tier"
    }
    premium {
        dimension "tier"
    }
    lightweight {
        dimension "distro"
    }
    heavy {
        dimension "distro"
    }
}

I'm trying to add a .jar dependency for the premium tier only. The way to add it is quite trivial:

premiumImplementation fileTree(dir: 'libs', include: ['*.jar']) // Works

The problem is that I have two versions of this .jar . One for each subversion mentioned above: lightweight and heavy.

I tried to apply the trivial solution to this type of dependency:

premiumLightweightImplementation fileTree(dir: 'libs', include: ['*lightweight.jar'])
premiumHeavyImplementation fileTree(dir: 'libs', include: ['*heavy.jar'])

But I get a gradle error:

Could not find method premiumLightweightImplementation() for arguments [directory 'libs']

Of course this also applies to premiumHeavyImplementation.

I'm sure there's a gradle-way to do what I'm asking. I found two options to deal with this issue:

  1. Stop using dimensions altogether (Bad solution, I'll have to write all the flavor-combinations myself).
  2. Implement a function which retrieves the current flavor I'm trying to assemble, and use its return value in a directory path. For example:

    def combination = getCurrentFlavorCombination()
    premiumImplementation fileTree(dir: "libs/$combination", include: ['*.jar'])

These are ugly and unreliable ways to achive this simple requirement: The premium tier should have a .jar linked to it - the version of that .jar depends on another dimension - distro.

I'm not asking for too much, but couldn't find in Gradle docs a nice way to do that. I only found ways to compile a library into jars, but mine already comes in jars, I only wish to link it appropriately. Maybe you guys can help me out here.

Thank you so much!

回答1:

I was going by this section of the Android Studio manual which states that you need to declare explicitly any configurations that for flavor/build type combinations. In this case, that means you need to add the following to your build script before the dependencies {} block:

configurations {
    freeLightweightImplementation
    freeHeavyImplementation
    premiumLightweightImplementation
    premiumHeavyImplementation
}