这里要用到 productFlavors ,productFlavors 能够用来自定义应用构建版本android
在 build.gradle文件中 android 目录下添加 如下代码便可android-studio
productFlavors { //默认,不设置 applicationId ,继承 defaultConfig 中的配置 flavors_default { } //开发版本, applicationId 替换为 com.xxx.dev flavors_dev { applicationId "com.xxx.dev" } //发布版本, applicationId 替换为 com.xxx.release flavors_release { applicationId "com.xxx.release" } }
该方案经过在 AndroidManifest.xml 文件中 application 标签下指定 <mate-data> 设置占位符来实现动态替换属性值。app
在 build.gradle文件中 ide
注:此方式能够能会引发异常以下gradle
Error:Execution failed for task ':app:processDebugManifest'. >Manifest merger failed with multiple errors, see logs
此问题产生缘由大概有三个:ui
1.清单文件有错,这种错不会在编译时指出来,固然as中仍是能够看到的debug
2.引入的三方包存在相同的label icon 等名字code
解决:清单文件用toolsorm
而后添加 replace字段
如 tools:replace="icon,label" 便可 xml
在 main 的同级目录下建立以渠道名命名的文件夹,而后建立资源文件(路径要与 main 中的一致),而后打包的时候 gradle 就会本身替换或者合并资源。
例如, App 的默认 icon 路径为 main\res\mipmap-hdpi\ic_launcher.png ,那么 flavors_dev的路径就为 flavors_dev\res\mipmap-hdpi\ic_launcher.png ,打包 flavors_dev 渠道的时候会自动替换图片。同理assets中文件以下:
使用 BuildConfig 的变量
当咱们定义以下字段以后,编译后自动生成文件,在 app/build/source/BuildConfig/dev/com.xxx.dev/BuildConfig 目录,
打开这个文件,咱们就能看到咱们所定义的字段了。
1.设置字段 使用 buildConfigField
设置好后编译一下,咦,什么鬼,怎么出错了?
明明设置的字符串怎么会这样,好了这是咱们须要注意的地方,设置值须要这样写
它的意思是 "default" 这个总体是属于一个字符串,而后在编译一下
恩,ok
2.使用字段
经常使用命令 看这里
gradlew assembleDebug
打包全部渠道的 debug 版本
gradlew assembleRelease
打包全部渠道的 release 版本
gradlew assembleflavors_devRelease
单独打包 flavors_dev 的 release 版本
gradlew assembleflavors_devDebug
单独打包 flavors_dev 的 Debug 版本