多渠道打包,Activity中获取配置信息

216 阅读1分钟

产品经理要求同一个APK,打包两个APK,分别有不同的界面启动背景图和主页有不同的显示,这就用到了多渠道打包。 在APK进行相应配置,实现多渠道打包。 首先在主程序下面的build.gradle中设置manifestPlaceholders: android {

productFlavors {
    //以下所有值有变更务必和ClientInfoBean同步修改
    officer {
        manifestPlaceholders = [CH_ADDRESS: "officer"] //值有变更务必和ClientInfoBean同步修改
    }
    //集约版本  
    channel_intensive {
        manifestPlaceholders = [channel_theme : "@style/SplashTheme_intensive",                                channel_type : "channel_intensive"]

    }
    //广西版本  
    channel_guangxi {
        manifestPlaceholders = [channel_theme : "@style/SplashTheme_guangxi",                                channel_type : "channel_guangxi"]
    }
}
}

上面就是打包一个集约版本,一个广西版本。对应的theme如下,channel_theme 是在程序对应的页面启动背景图设置theme的地方,通过windowBackground设置不同的背景图。下面在style.xml中写的两个theme,start_bg_2690​和start_bg_3914是两张图

<style name="SplashTheme_intensive" parent="Theme.AppCompat.NoActionBar">
    <!-- 将splash图片设置在这,这样这张图片取代白屏 -->
    <item name="android:windowBackground">@mipmap/start_bg_2690</item>
    <item name="android:windowTranslucentStatus">true</item>
    <item name="android:windowTranslucentNavigation">true</item>
</style>
<style name="SplashTheme_guangxi" parent="Theme.AppCompat.NoActionBar">
    <!-- 将splash图片设置在这,这样这张图片取代白屏 -->
    <item name="android:windowBackground">@mipmap/start_bg_3914</item>
    <item name="android:windowTranslucentStatus">true</item>
    <item name="android:windowTranslucentNavigation">true</item>
</style>

下面是MainActivity在AndroidManifest.xml中的设置,android:theme="${channel_theme}"获取到上面配置中的数据。

<application>
    <activity
        android:name="xxx.xxx.MainActivity"
        android:exported="true"
        android:screenOrientation="landscape"
        android:theme="${channel_theme}">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <meta-data android:name="main_start_bg" android:value="${channel_type}"></meta-data>
    </activity>

</application>

下一步,主页面MainActivity中要根据配置,获取目前的打包信息,上面需要配置,否则会报错。 在MainActivity获取 manifestPlaceholders 的值方法如下kotlin:

/**
 * 在Activity获取 manifestPlaceholders 的值
 * 注意:在AndroidManifest.xml
 * 该Activity标签下加上
 * <meta-data android:name="label111" android:value="${label}"></meta-data>
 * @param context
 * @param key
 * @return
 */
fun getActivityPlaceholders(context: Context, key: String?): String? {
    var placeholdersValues = ""
    try {
        val appInfo: ActivityInfo = context.getPackageManager()
            .getActivityInfo((context as Activity).componentName, PackageManager.GET_META_DATA)
        val metaData = appInfo.metaData ?: return ""
        placeholdersValues = metaData.getString(key).toString()
    } catch (e: PackageManager.NameNotFoundException) {
        e.printStackTrace()
    }
    return placeholdersValues
}

调用如下:

var channelType = getActivityPlaceholders(this,"main_start_bg")