w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How to replace a string for a buildvariant with gradle in android studio?

I solved the problem on my own, so here is the solution "step by step" - perhaps it will help some other newbies to gradle :)

  • Copy Task in General:
copy{
    from("pathToMyFolder"){
        include "my.file"
    }
    // you have to use a new path for youre modified file
    into("pathToFolderWhereToCopyMyNewFile")
}
  • Replace a line in General:
filter{
    String line -> line.replaceAll("<complete line of regular
expression>",
                                   "<complete line of modified
expression>")
}
  • I think the biggest problem was to get the right paths, because I had to make this dynamically (this link was very helpful for me). I solved my problem by replacing the special lines in the manifest and not in the String-file.

  • The following example shows how to replace the "meta-data"-tag in the manifest to use youre google-maps-api-key (in my case there are different flavors that use different keys ):

android.applicationVariants.each{ variant -> 
    variant.processManifest.doLast{ 
        copy{
            from("${buildDir}/manifests"){
                include "${variant.dirName}/AndroidManifest.xml"
            }
            into("${buildDir}/manifests/$variant.name")

            // define a variable for your key:
            def gmaps_key = "<your-key>"

            filter{
                String line -> line.replaceAll("<meta-data
android:name="com.google.android.maps.v2.API_KEY" android:value=""/>",
                                               "<meta-data
android:name="com.google.android.maps.v2.API_KEY" android:value="" +
gmaps_key + ""/>")
            }

            // set the path to the modified Manifest:
            variant.processResources.manifestFile =
file("${buildDir}/manifests/${variant.name}/${variant.dirName}/AndroidManifest.xml")
        }    
   }
}




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.