如何根据gradle风格设置variables

我想通过一个variablestest ,我设置不同的味道作为NDK定义。 但由于某种原因,他总是传递最后一种味道的价值。

这里是build.gradle

 apply plugin: 'com.android.library' def test android { compileSdkVersion 23 buildToolsVersion "23.0.2" defaultPublishConfig "flavorARelease" publishNonDefault true defaultConfig { minSdkVersion 15 targetSdkVersion 17 ndk { moduleName "test" ldLibs "log" } } productFlavors { flavorA { test = 1 } flavorB { test = 2 } } buildTypes { debug { ndk { if (cFlags == null) { cFlags = "" } cFlags = cFlags + " -DLOGGING=1 -DTEST="+test+" " } minifyEnabled false } release { ndk { if (cFlags == null) { cFlags = "" } cFlags = cFlags + " -DLOGGING=0 -DTEST="+test+" " } minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.1.1' } 

这里是生成的Android.mk中的CFLAG行

build立/中间体/ NDK / flavorA /debugging/ Android.mk:

 LOCAL_CFLAGS := -DLOGGING=1 -DTEST=2 

我期望在这里-DTEST=1

build立/中间体/ NDK / flavorB /debugging/ Android.mk:

 LOCAL_CFLAGS := -DLOGGING=1 -DTEST=2 

那么我的错误在哪里? 或者我怎样才能实现自己的目标? 请考虑一下,真正的问题是更复杂的,如果可能的话,我想在“buildTypes”段中定义这些定义。

Solutions Collecting From Web of "如何根据gradle风格设置variables"

我find了解决办法:

首先而不是def test为所有productFlavors指定一个新的字段

 productFlavors.all { ext.dTest = null } 

然后这个字段被设置在每个风味(代码不变)

 productFlavors { flavorA { dTest = 1 } flavorB { dTest = 2 } } 

最后你可以在buildTypes中做到这一点

 buildTypes { all { productFlavors { all { ndk { if (cFlags == null) { cFlags = "" } cFlags = cFlags + " -DTEST="+dTest+" " } } } } debug { minifyEnabled false ndk { if (cFlags == null) { cFlags = "" } cFlags = cFlags + " -DLOGGING=1 " } } release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' ndk { if (cFlags == null) { cFlags = "" } cFlags = cFlags + " -DLOGGING=0 " } } } 

这里是完整的文件:

 apply plugin: 'com.android.library' android { compileSdkVersion 23 buildToolsVersion "23.0.2" defaultPublishConfig "flavorARelease" publishNonDefault true defaultConfig { minSdkVersion 15 targetSdkVersion 17 ndk { moduleName "dTest" ldLibs "log" } } productFlavors.all { ext.dTest = null } productFlavors { flavorA { dTest = 1 } flavorB { dTest = 2 } } buildTypes { all { productFlavors { all { ndk { if (cFlags == null) { cFlags = "" } cFlags = cFlags + " -DTEST="+dTest+" " } } } } debug { minifyEnabled false ndk { if (cFlags == null) { cFlags = "" } cFlags = cFlags + " -DLOGGING=1 " } } release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' ndk { if (cFlags == null) { cFlags = "" } cFlags = cFlags + " -DLOGGING=0 " } } } } 

你可以使用buildConfigField

 productFlavors { demo { buildConfigField "int", "FOO", "1" buildConfigField "String", "FOO_STRING", "\"foo1\"" } full { buildConfigField "int", "FOO", "2" buildConfigField "String", "FOO_STRING", "\"foo2\"" } }