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

后端 未结 4 437
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  -上瘾入骨i
    2020-12-01 04:13

    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:

      copy {
         ...
         filter{
             String line -> line.replaceAll("",
                                            "")
         }
      }
      
    • 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 = ""
      
                  filter{
                      String line -> line.replaceAll("",
                                                     "")
                  }
      
                  // set the path to the modified Manifest:
                  variant.processResources.manifestFile = file("${buildDir}/manifests/${variant.name}/${variant.dirName}/AndroidManifest.xml")
              }    
         }
      }
      

提交回复
热议问题