How to replace a string for a buildvariant with gradle in android studio?

后端 未结 4 442
没有蜡笔的小新
没有蜡笔的小新 2020-12-01 03:54

I have two flavors of my project:

flavor1 -> packagename: com.example.flavor1 
flavor2 -> packagename: com.example.flavor2

Now I want

4条回答
  •  隐瞒了意图╮
    2020-12-01 04:18

    I use almost exactly the approach you wanted to. The replaceInManfest is also generic and can be used for other placeholders as well. The getGMapsKey() method just returns the appropriate key based on the buildType.

    applicationVariants.all { variant ->
        def flavor = variant.productFlavors.get(0)
        def buildType = variant.buildType
        variant.processManifest.doLast {
            replaceInManifest(variant,
                'GMAPS_KEY',
                getGMapsKey(buildType))
        }
    }
    
    def replaceInManifest(variant, fromString, toString) {
        def flavor = variant.productFlavors.get(0)
        def buildtype = variant.buildType
        def manifestFile = "$buildDir/manifests/${flavor.name}/${buildtype.name}/AndroidManifest.xml"
        def updatedContent = new File(manifestFile).getText('UTF-8').replaceAll(fromString, toString)
        new File(manifestFile).write(updatedContent, 'UTF-8')
    }
    

    I have it up on a gist too if you want to see if it evolves later.

    I found this to be a more elegant and generalizable approach than the others (although the token replacement just working would have been nicer).

提交回复
热议问题