项目中我有多个activity想设置为启动的Activity,也就是设置成MainActivity,需要在Manifest中对activity配置:
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
......
</intent-filter>
如果每次编译版本都去手动修改的话,不仅麻烦还容易忘记。
可以用gradle配置来解决这个问题。
defaultConfig {
......
// 先在默认配置中定义两个变量main_activity_key和oem_main_activity_key,并赋初始值
manifestPlaceholders += [main_activity_key: "android.intent.action.MAIN",
oem_main_activity_key: "android.intent.action.NO_MAIN"]
//不能当独写两个manifestPlaceholders,必须是一个数组,不然编译通不过
......
}
// 客户版本
productFlavors {
OemA {
buildConfigField "int", "oem_type", "0"
}
OemB {
buildConfigField "int", "oem_type", "0"
}
}
现在我的OemA客户和OemB客户,各自都有自己的MainActivity.
<activity
android:name=".ui.activity.OemAActivity"
android:launchMode="singleInstance"
android:screenOrientation="landscape"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".ui.activity.OemBActivity"
android:launchMode="singleInstance"
android:screenOrientation="landscape"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
现在我想在编译OemA的时候,把OemAActivity变成MainActivity,而OemBActivity为非MainActivity.
// 遍历OEM版本,在目标客户中根据需要替换main_activity_key和oem_main_activity_key的值
productFlavors.all {
flavor ->
if (flavor.name.contains("OemA")) {
flavor.manifestPlaceholders = [main_activity_key: "android.intent.action.NO_MAIN",
oem_main_activity_key: "android.intent.action.MAIN"]
}
else if (flavor.name.contains("OemB")) {
flavor.manifestPlaceholders = [main_activity_key: "android.intent.action.MAIN",
oem_main_activity_key: "android.intent.action.NO_MAIN"]
}
}
然后在Manifest中修改两个Activity的action属性
<activity
android:name=".ui.activity.OemAActivity"
android:excludeFromRecents="true"
android:launchMode="singleInstance"
android:screenOrientation="landscape"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
<intent-filter>
<action android:name="${oem_main_activity_key}"/> // 修改属性
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".ui.activity.OemBActivity"
android:excludeFromRecents="true"
android:launchMode="singleInstance"
android:screenOrientation="landscape"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
<intent-filter>
<action android:name="${main_activity_key}"/> // 修改属性
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
最后编译 gradlew assembleOemARelease