简体   繁体   中英

Reading metadata from build.gradle

According to this I can create several "flavors" in my Android Studio project. But, it looks like I can only create two trees that then will be built.

Is it possible to add variables in my build.gradle file, that I can then access from code, so that I can have a more fine-grained control on how my app will be built?

Eg in my build.gradle :

productFlavors {
    free {
        applicationId "com.example.app.free"
        showAds "yes"
    }
    full {
        applicationId "com.example.app.full"
        showAds "no"
    }
}

and then in my code

String showAds = Gradle.getString("showAds");
if ("yes".equals(showAds)) {
     // show ads
}

Is it possible to add variables in my gradle.build file, that I can then access from code, so that I can have a more fine-grained control on how my app will be built?

I presume you really mean your build.gradle file.

For your specific case, you could just use the already-existing BuildConfig.FLAVOR , which will be free or paid .

Or, you can use buildConfigField to add your own fields to BuildConfig :

productFlavors {
    free {
        applicationId "com.example.app.free"
        buildConfigField "boolean", "I_CAN_HAZ_ADS", 'true'
    }
    full {
        applicationId "com.example.app.full"
        buildConfigField "boolean", "I_CAN_HAZ_ADS", 'false'
    }
}

Then, you would refer to BuildConfig.I_CAN_HAZ_ADS in your Java code.

Note that I have only used BuildConfig field for String types, not boolean . AFAIK, any simple type like this should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM