How to replace strings resources with Android Gradle

前端 未结 4 954
感动是毒
感动是毒 2020-12-07 23:45

I made a new app with gradle in Android Studio, and now I need to make about 10 versions with different package names and values in resources. I made custom flavors as in ex

4条回答
  •  心在旅途
    2020-12-08 00:13

    I had a similar problem. I wanted to add the Jenkins build number to the strings that get merged from strings.xml. Here's my solution as of Android Gradle plugin 0.12.+.

    // Insert the build number into strings.xml
    android.applicationVariants.all{ variant ->
        variant.mergeResources.doLast{
            ext.env = System.getenv()
            def buildNumber = env.BUILD_NUMBER
            if (buildNumber != null) {
                File valuesFile = file("${buildDir}/intermediates/res/${variant.dirName}/values/values.xml")
                println("Replacing revision number in " + valuesFile)
                println("Build number = " + buildNumber)
                String content = valuesFile.getText('UTF-8')
                content = content.replaceAll(/devBuild/, buildNumber)
                valuesFile.write(content, 'UTF-8')
            }
        }
    }
    

    You might want to hook into a different Gradle task depending on what you want to do. Take a look at the tasks that are part of the Android build to figure that out.

    http://tools.android.com/tech-docs/new-build-system/user-guide

    UPDATE: At some point, the Android Gradle plugin changed the way to iterate through application variants keyword from each to all. My answer has been updated to reflect the change, but try switching to each if this code doesn't print anything to the console.

提交回复
热议问题