15

I'm using AndroidStudio and I have the following:

  • Main Android project: app
  • Java Library: communication

I want to set up my "communication" module's gradle file to achieve the following:

  • As app module's gradle, I can setup variables for BuildConfig.java file, e.g.:

    buildTypes {
        release {
            ...
            buildConfigField "String", "SERVER_URL", '"my_url"'
        }
    
        debug {
            buildConfigField "String", "SERVER_URL", '"my_url"'
        }
    }
    

and then I can use them using BuildConfig.SERVER_URL

The question is: How do I achieve this using a Java Library module?

Antonio
  • 11,395
  • 6
  • 33
  • 48

2 Answers2

6

I think that you are looking for this Gradle plugin. It brings BuildConfig to pure Java module.

https://github.com/mfuerstenau/gradle-buildconfig-plugin

Vojtěch Sázel
  • 530
  • 5
  • 14
  • Oh, that’s interesting. I’ll try to test it on these days. Cannot do it atm – Antonio Jan 19 '18 at 14:06
  • If you are looking for Kotlin support too, I've made this one: https://github.com/gmazzo/gradle-buildconfig-plugin – gmazzo Mar 28 '19 at 17:50
  • @gmazzo how to add release and debug flavors of configs? – Sundara Raghavan Dec 16 '19 at 13:15
  • Multi Flavor/Variants is an Android feature, but you may archieve something simillar by creating two SourceSets, debug and release, and making them extend from the main one. Then you may use my plugin to setup buildConfigFields on them – gmazzo Dec 17 '19 at 17:00
1

If by Java library you mean Android module then :

Set buildTypes variables inside the build.gradle file into library module like app module.

Get it by using the correct BuildConfig Class.

  • my.package.app.BuildConfig.APP_VARIABLE
  • my.package.library.BuildConfig.LIBRARY_VARIABLE

In other way, maybe you can take a look to gradle task and System Environment this answer can help you https://stackoverflow.com/a/25714617/4681367

There is no other way to get build configuration outside an Android module.

Just set/add an environment variable based on your android BuildConfig variables.

Community
  • 1
  • 1
Lionel Briand
  • 1,447
  • 10
  • 21
  • 2
    Thanks for your answer, @Lionel. It is not an Android based project-module. It is a Java module that has `plugin 'java'` – Antonio Jun 04 '16 at 21:08
  • This helped my for Android in this case. A simple Java class that needs a reference from a product flavor. BuildConfig.MYVALUE did the trick. great! – CaptainCrunch Jun 01 '21 at 18:05