【问题标题】:builg.gradle: how to execute code only on selected flavorbuild.gradle:如何仅在选定的风味上执行代码
【发布时间】:2015-02-09 11:46:07
【问题描述】:

我在我的 Android 项目 build.gradle 中声明了这个函数:

def remoteGitVertsion() {
  def jsonSlurper = new JsonSlurper()
  def object = jsonSlurper.parse(new URL("https://api.github.com/repos/github/android/commits"))
  assert object instanceof List
  object[0].sha
}

还有这种味道:

android {
  ...
  productFlavors {
    internal {
      def lastRemoteVersion = remoteGitVersion()
      buildConfigField "String", "LAST_REMOTE_VERSION", "\"" + lastRemoteVersion + "\""
    }
    ...
  }
  ...
}

现在,由于 gradle 声明性质,每次构建项目时都会执行 remoteGitVersion 函数,无论构建风格是内部的还是其他的都无关紧要。因此,github API 调用配额被消耗,过了一会儿,我收到了一条很好的禁止消息。

我怎样才能避免这种情况? Is it possible to execute the function only when the selected flavor is the right one?

【问题讨论】:

  • 这是一个很酷的主意。希望我能给你一个答案

标签: android gradle


【解决方案1】:

从这里参考:

In Android/Gradle how to define a task that only runs when building specific buildType/buildVariant/productFlavor (v0.10+)

回顾一下:

1。将您的风味特定逻辑包装到任务中

task fetchGitSha << {
    android.productFlavors.internal {
        def lastRemoteVersion = remoteGitVersion()
        buildConfigField "String", "LAST_REMOTE_VERSION", "\"" + lastRemoteVersion + "\""
    }
}

2。每当您构建您的变体时,才调用该任务。

根据您的情况,您可以使用 assembleInternalDebug 连接。

tasks.whenTaskAdded { task ->
    if(task.name == 'assembleInternalDebug') {
        task.dependsOn fetchGitSha
    }
}

3。确保从风味定义中删除动态内容

productFlavors {
    internal {
        # no buildConfigField here
    }
}

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多