Android 通过配置 productFlavors 实现多版本差异化打包

0.效果

开发过程中,因为种种原因,有时需要在同一手机上安装测试版和生产版,所需效果如下:

1.创建productFlavors

在APP的gradle中添加:

android {
    ...
    //创建productFlavors
    productFlavors {
        ceshi{//配置测试版包名和应用名
            applicationId "ceshi.yb.com.wanandroid"
            manifestPlaceholders = [APP_NAME: "@string/app_name_ceshi"]
        }
        shengchan{//配置生产版包名和应用名
            applicationId "shengchan.yb.com.wanandroid"
            manifestPlaceholders = [APP_NAME: "@string/app_name_shengchan"]
        }

    }
}

此时应该报以下错误:
Error:All flavors must now belong to a named flavor dimension. Learn more at https://d.android.com/r/tools/flavorDimensions-missing-error-message.html

在defaultConfig 中加上:

defaultConfig {
        ...
        flavorDimensions "versionCode"
    }

再重新编译下就OK了.

2.创建统一文件夹

切换到Project模式的目录:


在src目录下新建ceshi(/shengchan)包:


再新建以下包和文件:


资源文件同:


调试时点击 Build Variant 选择自己需要的版本即可正常引用



3.配置不同的应用名或其他属性

首先strings.xml中添加:

    <string name="app_name_ceshi">测试版WanAndroid</string>
    <string name="app_name_shengchan">生产版WanAndroid</string>

然后manifest中改下lable:

<application
        android:name=".base.BaseApp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="${APP_NAME}"//引用gradle中定义的变量
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".ui.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ui.ImgDetailActivity"></activity>

    </application>

打包时同时选择两个即可:



源码已提交到GitHub,可以的话请顺便点个小星星。








  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值