How to Modify Code Between Product Flavors
Asked Answered
W

2

5

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?

Wismar answered 13/3, 2014 at 3:42 Comment(0)
S
5

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.

Salish answered 11/7, 2014 at 21:13 Comment(0)
R
3

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

Rostock answered 19/9, 2017 at 8:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.