使用manifestPlaceholders

发现前几天 Android Studio Gradle Plugin 发布了0.13.0版, 终于支持Gradle 2.1了。其中Product Flavors能支持AndroidManifest placeholder了,赶紧应用起来。

比如我需要打包不同渠道的APK,需要在AndroidManifest中定义渠道名称,以便在java中调用。以前ant或gradle打包时动态改变渠道的思路是:正则AndroidManifest的特定字符然后替换。新版本直接可以省掉自己编写正则的过程啦。

旧版gradle编写(参考友盟渠道打包

AndroidManifest.xml

<meta-data  
    android:name="channel"      
    android:value="CHANNEL_VALUE"/>

builde.gradle

android {  
  productFlavors {
      "xiaomi"{}
      "360market"{}
      "baidu"{}
      "wandoujia"{}
  }

  applicationVariants.all { variant ->
      variant.processManifest.doLast {
          def manifestFilePath = "${buildDir}/intermediates/manifests/${variant.dirName}/AndroidManifest.xml"
          def updatedContent = new File(manifestFilePath).getText('UTF-8').
                  replaceAll("CHANNEL_VALUE", "${variant.productFlavors[0].name}")
          new File(manifestFilePath).write(updatedContent, 'UTF-8')
          def manifestFile = file(
                  "${buildDir}/intermediates/manifests/${variant.dirName}/AndroidManifest.xml")
          variant.processResources.manifestFile = manifestFile
      }
  }
}

而在新版中,可以这样写。

AndroidManifest.xml

<meta-data  
    android:name="channel"      
    android:value="${channelName}"/>

builde.gradle

android {  
  productFlavors {
      "xiaomi"{
          manifestPlaceholders = [channelName: "xiaomi"]
      }
      "360market"{
          manifestPlaceholders = [channelName: "360market"]
      }
      "baidu"{
          manifestPlaceholders = [channelName: "baidu"]
      }
      "wandoujia"{
          manifestPlaceholders = [channelName: "wandoujia"]
      }
  }  
}

或者可以批量修改

android {  
  productFlavors {
      "xiaomi"{}
      "360market"{}
      "baidu"{}
      "wandoujia"{}
  }  

  productFlavors.all { 
          flavor -> flavor.manifestPlaceholders = [channelName: name] 
  }
}

顿时清晰了很多有没有~

PS:新版Gradle Plugin在编译输出的AndroidManifest.xml 路径也变了。所以才赶紧改成用manifestPlaceholders的方式……

Author

Relex

Android Developer