0

I have an application with 2 product flavors and as a result 4 build variants:

1) freeDebug
2) freeRelease
3) paidDebug
4) paidRelease

I have a Fragment that contains an ad, and it takes 2 lines to implement:

@Nullable @BindView (R.id.bottomsheet_ad) AdView mAdView;
mAdView.loadAd(adRequest);

So because of 2 lines, I have to potentially maintain 2 or more files.

I'm considering 2 solutions:

1) Check flavor at runtime:

if (BuildConfig.FLAVOR.equals("flavor123")) {
    ...
}

2) Create a common flavor and point needed variants in gradle, as explained here:

android {
    ...
    productFlavors {
        flavorOne {
            ...
        }
        flavorTwo {
            ...
        }
        flavorThree {
            ...
        }
        flavorFour {
            ...
        }
    }
    sourceSets {
        flavorOne.java.srcDir 'src/common/java'
        flavorTwo.java.srcDir 'src/common/java'
        flavorThree.java.srcDir 'src/common/java'
    }
}

Which solution would be better? And is checking flavor at runtime as above considered polluting the code?

Suleyman
  • 2,765
  • 2
  • 18
  • 31
  • 2
    IMHO, a better option than those two is to use `buildConfigField` to define a custom flag in your Gradle script, then branch your code based on that flag. In other words, do not depend on `BuildConfig.FLAVOR`, but `BuildConfig.DO_WE_SHOW_AN_AD_HERE`. – CommonsWare Jul 01 '19 at 19:45
  • If your only concern is about this `Ad`, I'd use stubs and provide an empty impl per flavor (and wouldn't bother making the project more complicated). But it really depends on so many factors it's hard to tell. I wouldn't do the `if` in the code. Or as suggested above ^ use buildConfig flags (tho I usually use these to turn features off for debug, not per flavor) – Martin Marconcini Jul 01 '19 at 19:45
  • @CommonsWare Thanks a lot for the suggestion, I'll give it a go, looks like a more neat way to do it. – Suleyman Jul 01 '19 at 19:53
  • @MartinMarconcini That's a really nice option, I haven't thought of that. I'll try CommonsWare's suggestion and this one as well. Thank you! – Suleyman Jul 01 '19 at 19:56

1 Answers1

4

You can add something like following to appropriate flavor in your build.gradle

buildConfigField "boolean", "showAds", 'true'

And then use like following (your main src files will still be used for additional flavors you add):

if (BuildConfig.showAds) {

}
John O'Reilly
  • 10,000
  • 4
  • 41
  • 63