如何在 gradle 中获取当前风味

时间:2023-02-15
本文介绍了如何在 gradle 中获取当前风味的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用有两种产品风格:

I have two product flavors for my app:

productFlavors {
    europe {
        buildConfigField("Boolean", "BEACON_ENABLED", "false")
    }

    usa {
        buildConfigField("Boolean", "BEACON_ENABLED", "true")
    }
}

现在我想在任务中获取当前风味名称(我在 Android Studio 中选择的名称)以更改路径:

Now I want to get the current flavor name (which one I selected in Android Studio) inside a task to change the path:

task copyJar(type: Copy) {
    from('build/intermediates/bundles/' + FLAVOR_NAME + '/release/')
}

如何在 Gradle 中获取 FLAVOR_NAME?

How can I obtain FLAVOR_NAME in Gradle?

谢谢

推荐答案

如何获取当前风味名称

我开发了以下函数,准确返回当前风味名称:

def getCurrentFlavor() {
    Gradle gradle = getGradle()
    String  tskReqStr = gradle.getStartParameter().getTaskRequests().toString()

    Pattern pattern

    if( tskReqStr.contains( "assemble" ) )
        pattern = Pattern.compile("assemble(\w+)(Release|Debug)")
    else
        pattern = Pattern.compile("generate(\w+)(Release|Debug)")

    Matcher matcher = pattern.matcher( tskReqStr )

    if( matcher.find() )
        return matcher.group(1).toLowerCase()
    else
    {
        println "NO MATCH FOUND"
        return ""
    }
}

你也需要

import java.util.regex.Matcher
import java.util.regex.Pattern

在开头或您的脚本中.在 Android Studio 中,这通过使用Make Project"或Debug App"按钮进行编译来工作.

at the beginning or your script. In Android Studio this works by compiling with "Make Project" or "Debug App" button.

def getCurrentVariant() {
    Gradle gradle = getGradle()
    String tskReqStr = gradle.getStartParameter().getTaskRequests().toString()

    Pattern pattern

    if (tskReqStr.contains("assemble"))
        pattern = Pattern.compile("assemble(\w+)(Release|Debug)")
    else
        pattern = Pattern.compile("generate(\w+)(Release|Debug)")

    Matcher matcher = pattern.matcher(tskReqStr)

    if (matcher.find()){
        return matcher.group(2).toLowerCase()
    }else{
        println "NO MATCH FOUND"
        return ""
    }
}

如何获取当前风味 applicationId

类似的问题可能是:如何获取 applicationId?同样在这种情况下,没有直接的方法来获取当前的风味 applicationId.然后我使用上面定义的getCurrentFlavor函数开发了一个gradle函数,如下:

How to get current flavor applicationId

A similar question could be: how to get the applicationId? Also in this case, there is no direct way to get the current flavor applicationId. Then I have developed a gradle function using the above defined getCurrentFlavor function as follows:

def getCurrentApplicationId() {
    def currFlavor = getCurrentFlavor()

    def outStr = ''
    android.productFlavors.all{ flavor ->

        if( flavor.name==currFlavor )
            outStr=flavor.applicationId
    }

    return outStr
}

瞧.

这篇关于如何在 gradle 中获取当前风味的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:如何修复“意外元素<查询>在“清单 下一篇:更新到 Android Build Tools 25.1.6 GCM/FCM 后出现 Incomp

相关文章

最新文章