How to access ext variables in Gradle

别等时光非礼了梦想. 提交于 2019-12-10 13:18:30

问题


I am trying to get the variable defined in a 3rd party library (fabric) to do a condition based on whether Crashlytics is enabled or not.

ext.enableCrashlytics = true

http://support.crashlytics.com/knowledgebase/articles/202938-gradle The variable can be configured in buildTypes or in flavors but I can't find a way to access it elsewhere in my build.gradle

I tried several things without any luck.

allprojects.getProperties().get("enableCrashlytics")
project.enableCrashlytics
project.ext.enableCrashlytics
allProjects.ext.enableCrashlytics

Anyone tried that before? The context I'm trying to do this is to write the fabric.properties file based on if it is enabled or not.

android.applicationVariants.all { variant ->
  ...
  //create fabric.properties
  ...
}

回答1:


You can define a property in your top-level build.gradle:

ext {
  myproperty = 12
}

Or an array:

ext {

    myarray = [
            name0     : "xx",
            name1     : "xx"
   ]
}

Then in each module you can use somenthig like:

rootProject.ext.myproperty
rootProject.ext.myarray.name0



回答2:


I know this question is old but I stumbled upon it while attempting to do a similar thing.

After trial and error and reading through the build system source I figured it out.

variants.all { variant ->
     println("${variant.name.capitalize()}")
     println(variant.getBuildType().myFoo)
     println("------")
}

With this you'll be able to read the ExtraPropertiesExtensions from the different variants.

My output:

Debug
true
------
Release
true
------
Something
false
------

Here are the files I looked through to figure it out: ApplicationVariantImpl and DefaultBuildType




回答3:


project.hasProperty 'propName'
(parens optional when possible in groovy, prefer 'String' over "GString")



来源:https://stackoverflow.com/questions/32635272/how-to-access-ext-variables-in-gradle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!