场景
在开发过程中,尤其是涉及到2B的产品,我们往往是在一个工程中做多个软件的定制开发,其中比较简单和常见的就是应用名称和应用logo的动态变更,这些变更跟app绑定,当App编译完成后就不再修改,这样的场景往往就是在打包编译是动态配置即可。
方法
这些需求其实Gradle已经为我们考虑到了,并且提供了一些可行的方案来支持。
- 方式一 :使用manifestPlaceholders
build.gradle脚本配置manifestPlaceholders
android {
... ...
defaultConfig {
... ...
manifestPlaceholders = [my_app_ame: "demo1", my_app_icon: "@mipmap/logo1"]
}
// 依据debug/release变动的话设置如下
buildTypes {
debug {
manifestPlaceholders = [my_app_ame: "demo1", my_app_icon: "@mipmap/logo1"]
}
}
flavorDimensions "app"
// 依据flavors变动的话设置如下
productFlavors {
autoTest {
// Assigns this product flavor to the "version" flavor dimension.
// This property is optional if you are using only one dimension.
dimension "app"
manifestPlaceholders = [my_app_ame: "demo1", my_app_icon: "@mipmap/logo1"]
}
appStore {
// Assigns this product flavor to the "version" flavor dimension.
// This property is optional if you are using only one dimension.
dimension "app"
manifestPlaceholders = [my_app_ame: "demo2", my_app_icon: "@mipmap/logo2"]
}
}
}
对应的AndroidManifest.xml
<application
android:icon="${my_app_icon}"
android:label="${my_app_ame}" >
···
</application >
- 方式二:使用resValue
build.gradle脚本配置
android {
... ...
defaultConfig {
... ...
}
flavorDimensions "app"
// 依据flavors变动的话设置如下
productFlavors {
autoTest {
// Assigns this product flavor to the "version" flavor dimension.
// This property is optional if you are using only one dimension.
dimension "app"
resValue("string", "my_app_ame", "demo1")
resValue("mipmap", "my_app_icon", "@mipmap/@mipmap/logo1")
}
appStore {
// Assigns this product flavor to the "version" flavor dimension.
// This property is optional if you are using only one dimension.
dimension "app"
resValue("string", "my_app_ame", "demo2")
resValue("mipmap", "my_app_icon", "@mipmap/@mipmap/logo2")
}
}
}
对应的AndroidManifest.xml
<application
android:icon="@mipmap/my_app_icon"
android:label="@string/my_app_ame"
android:roundIcon="@mipmap/my_app_icon">
···
</application>
在代码中使用
mTextView.setText(R.string. my_app_ame);
mImageView.setImageResource(R.mipmap.app_icon);
注:该方法在代码和布局文件中使用会爆红,但是不影响编译运行,该问题主要是由于resValue是由gradle提供的方法,是动态生成的,类似BuildConfig
生成的文件类似
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Automatically generated file. DO NOT MODIFY -->
<!-- Values from default config. -->
<string name="my_app_ame" translatable="false">appName</string>
</resources>