-->

How to Modify Code Between Product Flavors

2019-05-15 00:15发布

问题:

I'm creating a very simple app with a free and paid version, for this I'm using the great productFlavors feature in the Android Gradle plugin. I understand how the build.gradle file should be configured and have written it so my build options are;

  • freeRelease
  • freeDebug
  • paidRelease
  • PaidDebug

that looks as follows

buildTypes {
    release {
        runProguard false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        signingConfig signingConfigs.someconfig
    }
}
productFlavors {
    free {
        packageName "com.somepackagename.appfree"
    }
    paid {
        packageName "com.somepackagename.appPaid"
    }
}

Basically, all I'm trying to do is restrict a few features and add AdMod to the free version, how would I do that? Do I add if-else statements in my main java classes that check to see if it's free or paid? or can I overwrite java classes in the free directory? How should I go about doing this?

回答1:

You can encode things in the directory structure, e.g.:

src/
  main/                    # Common source and assets
    java/
    res/
    AndroidManifest.xml
  free/                    # Source and assets for the free flavour
    java/
    res/
    AndroidManifest.xml
  paid/                    # Source and assets for the paid flavour
    java/
    res/
    AndroidManifest.xml

The code and assets that are specific to one version or the other go into the specific directories. The manifests are merged. You can use the FLAVOR field generated into BuildConfig.java to base if-else statements on.

The SourceSets and Dependencies section of the Android-Gradle-Plugin user guide explains this in greater detail.



回答2:

Do I add if-else statements in my main java classes that check to see if it's free or paid?

Yes, you have to add if-else in your activities/fragments to check the flavour:

private void javaCode() {
    if (BuildConfig.FLAVOR.equals("paid")) {
        doIt();
    else {
        showOnlyInPaidAppDialog();
    }
}

Source: BuildConfig