如何在gradle脚本中获取运行Android Flavor名称 [英] How to get Running Android Flavor Name in gradle script

查看:1135
本文介绍了如何在gradle脚本中获取运行Android Flavor名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这次,我遇到了这个问题,我试图在gradle脚本中获得当前的风味.我已经尝试过在此处给出的答案如何在gradle中获得当前风味 没有运气.

This time I have this problem, I am trying to get the current flavor in a gradle script. I have tried the answers given here How to get current flavor in gradle without luck.

我还没有看到他们使用的一些答案

I haven seen in some answers that they use

// Get all flavors
android.productFlavors.all { flavor ->
if (flavor.name.equals("flavorName")) {
    // do what you like
}
// ...
}

但是我也没有运气,因为我遇到以下错误:>无法获得任务的未知属性'android'

But also I didn't have any luck with that because i get the following error: > Could not get unknown property 'android' for task

所以我不知道如何获得当前的风味,任何帮助将不胜感激,谢谢!!!

So I don't know how to get the current flavor, any help will be very appreciated thanks!!!

我需要做的是执行针对每种口味不同的一段代码,我目前的想法是知道所选的构建变体在任务中执行此操作,但是如果有其他方法可以执行这将是完美的.

What I need to do is to execute a piece of code that is diferent for each flavor, my current idea is to know the selected build variant to do this in a task, but if there is any othe way to do this would be perfect.

推荐答案

我已经在此处发布了可行的解决方案,是:

I already posted a working solution here, that is:

以下函数精确地返回当前风味名称:

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.

这篇关于如何在gradle脚本中获取运行Android Flavor名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆