变体
defaultConfig { ... } // 默认配置
buildTypes { // 编译类型,默认的就是debug,release
debug {...}
release {...}
}
flavorDimensions "default" // 注意 所有变种都必须属于一个指定的变种维度
productFlavors { // 渠道
staging {
applicationId "com.app.staging"
versionCode 1
versionName "1.0.0"
}
prod {
applicationId "com.app.prod"
versionCode 1
versionName "1.0.0"
}
}
build 变体:[staging,prod][Debug,Release]
对应的 APK:app-[staging,prod]-[debug,release].apk
Gradle 创建的 build 变体数量等于每个变种维度中的变种数量与您配置的 build 类型数量的乘积。当 Gradle 为每个 build 变体或对应的工件命名时,先显示属于较高优先级变种维度的产品变种,接着是较低优先级维度中的产品变种,再接着是 build 类型。
维度具体看官方文档的例子。
使用源代码集构建
gradle会优先查看变体的目录
配置app相关内容
android/app/src/main/AndroidManifest.xml
<application
android:name=".MainApplication"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:allowBackup="false"
android:theme="@style/AppTheme">
...
</application>
对应的是android/app/src/main/res/values里的strings.xml和styles.xml,如果多变种会优先读取相应目录下的.
// strings.xml
<resources>
<string name="app_name">app</string>
<string name="appCenterCrashes_whenToSendCrashes" moduleConfig="true" translatable="false">DO_NOT_ASK_JAVASCRIPT</string>
<string name="appCenterAnalytics_whenToEnableAnalytics" moduleConfig="true" translatable="false">ALWAYS_SEND</string>
<string moduleConfig="true" name="CodePushDeploymentKey">xxx</string>
<string name="default_notification_channel_id">Android</string>
</resources>
// styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="android:textColor">#000000</item>
</style>
</resources>
调试打包
// 调试
npx react-native run-android --variant=[staging,prod]Debug
// 打包apk
cd android && ./gradlew assemble[Staging,Prod]Release
// 打包aab
cd android && ./gradlew bundle[Staging,Prod]Release
注意: react native 0.73+ 改用–mode 而不是 --variant