Is it possible to declare a variable in Gradle usable in Java?

后端 未结 9 1475
春和景丽
春和景丽 2020-11-22 09:11

Is it possible to declare a variable in Gradle usable in Java ? Basically I would like to declare some vars in the build.gradle and then getting it (obviously) at build time

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 09:23

    An example of usage an Api App Key in an Android application (Java and XML)

    gradle.properties

    AppKey="XXXX-XXXX"
    

    build.gradle

    buildTypes {
    //...
        buildTypes.each {
            it.buildConfigField 'String', 'APP_KEY_1', AppKey
            it.resValue 'string', 'APP_KEY_2', AppKey
        }
    }
    

    Usage in java code

    Log.d("UserActivity", "onCreate, APP_KEY: " + getString(R.string.APP_KEY_2));
    
    BuildConfig.APP_KEY_1
    

    Usage in xml code

    
    
    • Link to an example of Api App Key usage in an Android application
    • Using String Constants Generated by Gradle Build Configurations

提交回复
热议问题