其他分享
首页 > 其他分享> > 在android的build.gradle中创建和访问productFlavor变量

在android的build.gradle中创建和访问productFlavor变量

作者:互联网

我有一个由CI构建并发布到HockeyApp的多风味项目.
每个flavor都有一个applicationId和一个apiToken,它存储在flavor本身中(将所有重要变量保存在一个地方):

    def token = null

    productFlavors {

    prod {
        applicationId "de.example.appname"

        buildConfigField 'String', 'FLAVOR_ID', '"0"'
        buildConfigField 'String', 'HOCKEY_APP_ID', '"1234567890"'

        token = "1q2w3e4r5t6z7u8i9o0p"
    }

    demo {
        applicationId "de.example.appname.demo"

        buildConfigField 'String', 'FLAVOR_ID', '"1"'
        buildConfigField 'String', 'HOCKEY_APP_ID', '"987654321"'

        token = "p0o9i8u7z6t5r4e3w2q1"
    }
}

在像“productFlavors”这样的级别上有hockeyApp-settings:

    hockeyapp {
       apiToken = token
       releaseType = 0
       notify = 0
       status = 1
       notesType = 1
       notes = "Uploaded with gradle"
    }

为了调试我构建的代码和通过终端上传.apk文件:

./gradlew uploadProdReleaseToHockeyApp [...]

不幸的是,prod-flavor的变量标记总是被demo-value覆盖.因此,在每次上传过程后,我都会遇到错误

Error response from HockeyApp: App could not be created.

因为gradle尝试使用demo-token上传prod-flavor.

这里有一些额外的基本数据

compileSdkVersion 24
buildToolsVersion "24.0.1"
compile 'net.hockeyapp.android:HockeySDK:4.0.0'
classpath 'com.android.tools.build:gradle:2.1.3'
classpath 'de.felixschulze.gradle:gradle-hockeyapp-plugin:3.5'

根据我的要求,是否有一个解决方案来定义flavor-variables并以显示的方式访问它们?

解决方法:

在这个特例中,我找到了以下答案:

添加hockeyapp-task并进行所需的修改

hockeyapp {
    apiToken = "not_required"
    releaseType = 0
    notify = 0
    status = 2
    teams = 1234
    notesType = 1
}

在下一步中添加基于flavor的gradle任务来修改你hockeyapp的apiToken:

task setDevReleaseApiToken << {
    hockeyapp.apiToken = "1234567890abcdefghijklmnopqrstuvwxyz"
}

task setProdReleaseApiToken << {
    hockeyapp.apiToken = "1234567890abcdefghijklmnopqrstuvwxyz"
}

这些任务在gradle的whenTaskAdded-task中调用,你可以像这样简单地“覆盖”它:

tasks.whenTaskAdded { task ->
    if (task.name == 'uploadDevReleaseToHockeyApp') {
        task.dependsOn 'setDevReleaseApiToken'
    } else if (task.name == 'uploadProdReleaseToHockeyApp') {
        task.dependsOn 'setProdReleaseApiToken'
    }
}

每次调用任务uploadDevReleaseToHockeyApp(手动或通过CI ..)时,都会调用任务setDevReleaseApiToken并分配相关的apiToken.

如果需要,为所有其他风格扩展此架构!

标签:android,gradle,android-gradle,build-gradle,hockeyapp
来源: https://codeday.me/bug/20190627/1309693.html