Gradle task to change a boolean in build config

末鹿安然 提交于 2019-12-09 16:46:54

问题


I would like to create a very simple task which change a boolean in my gradle config.

I work on an Android application which can be run with several profiles, and for each build a need to specify if in my code the app must fake the bluetooth or not.

My gradle (relevant code) :

def fakeBluetooth = "true"

buildTypes {
    debug {
        minifyEnabled false
        signingConfig android.signingConfigs.debug
        buildConfigField "boolean", "fakeBluetooth", fakeBluetooth
    }
    release {
        minifyEnabled true
        signingConfig android.signingConfigs.release
        buildConfigField "boolean", "fakeBluetooth", fakeBluetooth
    }
}

task noFakeBluetooth {
    fakeBluetooth = "false"
}

Example of use in my java code :

if (BuildConfig.fakeBluetooth) {
    processFictiveBluetoothService();
} else {
    // other case
}

Examples of use in command line :

./gradlew iDebug noFakeBluetooth

and

./gradlew iDebug

Problem : in both cases the value of fakeBluetooth is always "true" (with or without "noFakeBluetooth" in cmd line).


回答1:


You can use project properties to pass the value:

buildTypes {
    debug {
        minifyEnabled false
        signingConfig android.signingConfigs.debug
        buildConfigField "boolean", "fakeBluetooth", fakeBluetooth()
    }
    release {
        minifyEnabled true
        signingConfig android.signingConfigs.release
        buildConfigField "boolean", "fakeBluetooth", fakeBluetooth()
    }
}

def fakeBluetooth() {
    def value = project.getProperties().get("fakeBluetooth")
    return value != null ? value : "true"
}

And then you can pass the property with:

./gradlew iDebug -PfakeBluetooth=true



回答2:


This works

 android.defaultConfig.buildConfigField "String", "value", "1"



回答3:


I think the correct approach would be to define resource value for buildTypes or productFlavours:

resValue "string", "key", "value"

then read out from it inside your code like: getResources().getString(R.string.key);



来源:https://stackoverflow.com/questions/28474958/gradle-task-to-change-a-boolean-in-build-config

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