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模式的目录:


扫描二维码关注公众号,回复: 10844805 查看本文章

在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,可以的话请顺便点个小星星。








发布了43 篇原创文章 · 获赞 27 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/qq_30878303/article/details/79536921