Android APP的Gradle详解(五)

一.多渠道打包applicationVariants{}闭包初级讲解

 

1.需求

多渠道打包时,自定义打出的包的名称。

 

 

2.代码

APP的Gradle文件

apply plugin: 'com.android.application'

/** ext闭包 在本Gradle中配置 versionCode&versionName 本Gradle的defaultConfig{}包使用 */
ext {
    versionInt = 2
    versionString = "2.0.0"
    releaseTime = releaseTime()
}

android {

    compileSdkVersion 28
    /** defaultConfig闭包 默认配置 */
    defaultConfig {
        applicationId "com.wjn.okhttpmvpdemo"
        minSdkVersion 19
        targetSdkVersion 27
        versionCode versionInt
        versionName versionString
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    /** signingConfigs闭包 项目签名配置 */
    signingConfigs {
        release {
            storeFile file('C:\\Users\\wujianning\\AndroidStudioProjects\\demo\\OKHttpMVPDemo\\test.jks')
            storePassword '123456'
            keyAlias 'key0'
            keyPassword '123456'
            v1SigningEnabled true
            v2SigningEnabled true
        }

        debug {
            storeFile file('C:\\Users\\wujianning\\AndroidStudioProjects\\demo\\OKHttpMVPDemo\\test.jks')
            storePassword '123456'
            keyAlias 'key0'
            keyPassword '123456'
            v1SigningEnabled true
            v2SigningEnabled true
        }
    }

    /** buildTypes闭包 项目打包配置 比如是否混淆 是否压缩 是否支持调式等等 这里为了区分下面多渠道打包Debug包和Release包 在versionName后添加了不同的后缀*/
    buildTypes {
        release {
            minifyEnabled false
            debuggable false
            multiDexEnabled false
        }

        debug {
            minifyEnabled false
            debuggable true
            multiDexEnabled false
            buildConfigField "String", "MAPID", "\"" + rootProject.ext.android.mapId + "\""
        }
    }

    /** productFlavors闭包 多渠道打包 flavorDimensions属性确定维度 分支&免费付费 */
    flavorDimensions "branch", "free_pay"
    productFlavors {
        red {
            dimension "branch"
            applicationIdSuffix ".red"
            signingConfig signingConfigs.release
        }

        blue {
            dimension "branch"
            applicationIdSuffix ".blue"
            signingConfig signingConfigs.debug
        }

        free {
            dimension "free_pay"
            buildConfigField "boolean", "IS_FREE", "true"
        }

        pay {
            dimension "free_pay"
            buildConfigField "boolean", "IS_FREE", "false"
        }
    }

    /** variantFilter闭包 过滤变体 可以设置忽略那个包 比如这里过滤掉了不在列表中的包*/
    variantFilter { variant ->
        def needed = variant.name in [
                'redFreeRelease',
                'redFreeDebug',
                'redPayRelease',
                'redPayDebug',
                'blueFreeRelease',
                'blueFreeDebug',
                'bluePayRelease',
                'bluePayDebug',
        ]
        setIgnore(!needed)
    }

    /** compileOptions闭包 配置项目使用JDK1.8 */
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    /** applicationVariants闭包 配置项目打包包名 */
    android.applicationVariants.all {
        variant ->
            variant.outputs.all { output ->
                //按照规范获取outputFileName 同时outputFileName字段也是打包的名称 重要
                outputFileName = "OkHttp_" + "${defaultConfig.versionName}_${releaseTime()}" + "_${variant.productFlavors[0].name}.apk"
                //更新VersionName
                output.setVersionNameOverride(outputFileName)
            }
    }

    /** sourceSets闭包 配置项目文件 */
    sourceSets {

        /** 默认 配置项目文件 */
        main {
            jniLibs.srcDirs = ['libs']
            assets.srcDirs = ['src/main/assets']
        }

        /** blue包 配置项目文件 */
        blue {
            assets.srcDirs = ['../protectFileConfig/assets/blue']
        }

        /** red包 配置项目文件 */
        red {
            assets.srcDirs = ['../protectFileConfig/assets/red']
        }

    }

}

static def releaseTime() {
    return new Date().format("yyyyMMdd", TimeZone.getTimeZone("GMT+8"))
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:support-v4:27.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation 'io.reactivex:rxjava:1.3.2'
    implementation 'io.reactivex:rxandroid:1.2.1'
    implementation 'com.squareup.okhttp3:okhttp:3.9.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.6.0'
    implementation 'com.readystatesoftware.systembartint:systembartint:1.0.3'

    implementation 'com.squareup.retrofit2:retrofit:2.7.0'
    implementation 'com.github.bumptech.glide:glide:4.4.0'
}
包名规范

OkHttp_+versionName+"_"+时间+"_"+渠道名

 

Java代码

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String versionName = getVersionName();
        Log.d("MainActivity", "versionName----:" + versionName);
    }

    /**
     * 获取当前程序版本号名
     * android:versionName="2.0"
     */

    private String getVersionName() {
        PackageManager pm = getPackageManager();
        try {
            PackageInfo info = pm.getPackageInfo(getPackageName(), 0);
            return info.versionName;
        } catch (Exception e) {
            // 不会发生的异常
            return "";
        }
    }

}

 

 

3.验证

<1> 日志打印

D/MainActivity: versionName----:OkHttp_2.0.0_20170426_blue.apk

 

<2> 打包截图 

 

 

 

 

 

 

 

二.多渠道打包applicationVariants{}闭包高级讲解

 

1.简介

上述使用applicationVariants{}闭包简单粗暴的把所有八个包都更新的打出的包的名称和versionName。那么如果我们需要判断呢?比如有些包需要拼字符串,有些包不需要。代码实现下面讲解

 

 

2.代码

apply plugin: 'com.android.application'

/** ext闭包 在本Gradle中配置 versionCode&versionName 本Gradle的defaultConfig{}包使用 */
ext {
    versionInt = 2
    versionString = "2.0.0"
    releaseTime = releaseTime()
}

android {

    compileSdkVersion 28
    /** defaultConfig闭包 默认配置 */
    defaultConfig {
        applicationId "com.wjn.okhttpmvpdemo"
        minSdkVersion 19
        targetSdkVersion 27
        versionCode versionInt
        versionName versionString
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    /** signingConfigs闭包 项目签名配置 */
    signingConfigs {
        release {
            storeFile file('C:\\Users\\wujianning\\AndroidStudioProjects\\demo\\OKHttpMVPDemo\\test.jks')
            storePassword '123456'
            keyAlias 'key0'
            keyPassword '123456'
            v1SigningEnabled true
            v2SigningEnabled true
        }

        debug {
            storeFile file('C:\\Users\\wujianning\\AndroidStudioProjects\\demo\\OKHttpMVPDemo\\test.jks')
            storePassword '123456'
            keyAlias 'key0'
            keyPassword '123456'
            v1SigningEnabled true
            v2SigningEnabled true
        }
    }

    /** buildTypes闭包 项目打包配置 比如是否混淆 是否压缩 是否支持调式等等 这里为了区分下面多渠道打包Debug包和Release包 在versionName后添加了不同的后缀*/
    buildTypes {
        release {
            minifyEnabled false
            debuggable false
            multiDexEnabled false
        }

        debug {
            minifyEnabled false
            debuggable true
            multiDexEnabled false
            buildConfigField "String", "MAPID", "\"" + rootProject.ext.android.mapId + "\""
        }
    }

    /** productFlavors闭包 多渠道打包 flavorDimensions属性确定维度 分支&免费付费 */
    flavorDimensions "branch", "free_pay"
    productFlavors {
        red {
            dimension "branch"
            applicationIdSuffix ".red"
            signingConfig signingConfigs.release
        }

        blue {
            dimension "branch"
            applicationIdSuffix ".blue"
            signingConfig signingConfigs.debug
        }

        free {
            dimension "free_pay"
            buildConfigField "boolean", "IS_FREE", "true"
        }

        pay {
            dimension "free_pay"
            buildConfigField "boolean", "IS_FREE", "false"
        }
    }

    /** variantFilter闭包 过滤变体 可以设置忽略那个包 比如这里过滤掉了不在列表中的包*/
    variantFilter { variant ->
        def needed = variant.name in [
                'redFreeRelease',
                'redFreeDebug',
                'redPayRelease',
                'redPayDebug',
                'blueFreeRelease',
                'blueFreeDebug',
                'bluePayRelease',
                'bluePayDebug',
        ]
        setIgnore(!needed)
    }

    /** compileOptions闭包 配置项目使用JDK1.8 */
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    /** applicationVariants闭包 配置项目打包包名 */
    android.applicationVariants.all {
        variant ->
            variant.outputs.all { output ->
                //获取分支 red&blue
                def appBranch = variant.productFlavors[0].name
                //获取免费付费  free&pay
                def free_pay = variant.productFlavors[1].name
                //默认的包名
                def result = "OkHttp_" + versionString
                //操作包名 blue的包 拼后面的字符串 red的包使用默认的字符串不需要拼后面的字符串
                if (appBranch == "blue") {
                    result = result + "_" + free_pay.toUpperCase() + "_" + releaseTime() + ".apk"
                } else {
                    result = result + ".apk"
                }
                //更新打出的包的名称
                outputFileName = result
                //更新VersionName
                output.setVersionNameOverride(result)
            }
    }

    /** sourceSets闭包 配置项目文件 */
    sourceSets {

        /** 默认 配置项目文件 */
        main {
            jniLibs.srcDirs = ['libs']
            assets.srcDirs = ['src/main/assets']
        }

        /** blue包 配置项目文件 */
        blue {
            assets.srcDirs = ['../protectFileConfig/assets/blue']
        }

        /** red包 配置项目文件 */
        red {
            assets.srcDirs = ['../protectFileConfig/assets/red']
        }

    }

}

static def releaseTime() {
    return new Date().format("yyyyMMdd", TimeZone.getTimeZone("GMT+8"))
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:support-v4:27.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation 'io.reactivex:rxjava:1.3.2'
    implementation 'io.reactivex:rxandroid:1.2.1'
    implementation 'com.squareup.okhttp3:okhttp:3.9.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.6.0'
    implementation 'com.readystatesoftware.systembartint:systembartint:1.0.3'

    implementation 'com.squareup.retrofit2:retrofit:2.7.0'
    implementation 'com.github.bumptech.glide:glide:4.4.0'
}

 

 

3.验证

打出八个包截图

 

打出八个包清单文件(顺序和上面截图一致)

android:versionName="OkHttp_2.0.0_FREE_20170426.apk"


android:versionName="OkHttp_2.0.0_FREE_20170426.apk"


android:versionName="OkHttp_2.0.0_PAY_20170426.apk"


android:versionName="OkHttp_2.0.0_PAY_20170426.apk"


android:versionName="OkHttp_2.0.0.apk"


android:versionName="OkHttp_2.0.0.apk"


android:versionName="OkHttp_2.0.0.apk"


android:versionName="OkHttp_2.0.0.apk"

 

 

 

 

 

 

 

三.多渠道打包 不同包使用不同的依赖

 

1.需求

多渠道打包时,不同的包使用不同的依赖。依赖可能是本地依赖或者本地库依赖。比如某些第三方的SDK会提供两个Jar包,Debug包依赖XXXDebugSDK.jar包,Release包依赖XXXReleaseSDK.jar包。

 

 

2.代码

apply plugin: 'com.android.application'

android {

    compileSdkVersion 28
    /** defaultConfig闭包 默认配置 */
    defaultConfig {
        applicationId "com.wjn.okhttpmvpdemo"
        minSdkVersion 19
        targetSdkVersion 27
        versionCode rootProject.ext.android.versionInt
        versionName rootProject.ext.android.versionString
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    /** signingConfigs闭包 项目签名配置 */
    signingConfigs {
        release {
            storeFile file('C:\\Users\\wujianning\\AndroidStudioProjects\\demo\\OKHttpMVPDemo\\test.jks')
            storePassword '123456'
            keyAlias 'key0'
            keyPassword '123456'
            v1SigningEnabled true
            v2SigningEnabled true
        }

        debug {
            storeFile file('C:\\Users\\wujianning\\AndroidStudioProjects\\demo\\OKHttpMVPDemo\\test.jks')
            storePassword '123456'
            keyAlias 'key0'
            keyPassword '123456'
            v1SigningEnabled true
            v2SigningEnabled true
        }
    }

    /** buildTypes闭包 项目打包配置 比如是否混淆 是否压缩 是否支持调式等等 这里为了区分下面多渠道打包Debug包和Release包 在versionName后添加了不同的后缀*/
    buildTypes {
        release {
            minifyEnabled false
            debuggable false
            multiDexEnabled false
            versionNameSuffix '-Release'
        }

        debug {
            minifyEnabled false
            debuggable true
            multiDexEnabled false
            versionNameSuffix '-Debug'
            buildConfigField "String", "MAPID", "\"" + rootProject.ext.android.mapId + "\""
        }
    }

    /** productFlavors闭包 多渠道打包 flavorDimensions属性确定维度 分支&免费付费 */
    flavorDimensions "branch", "free_pay"
    productFlavors {
        red {
            dimension "branch"
            applicationIdSuffix ".red"
            signingConfig signingConfigs.release
        }

        blue {
            dimension "branch"
            applicationIdSuffix ".blue"
            signingConfig signingConfigs.debug
        }

        free {
            dimension "free_pay"
            buildConfigField "boolean", "IS_FREE", "true"
        }

        pay {
            dimension "free_pay"
            buildConfigField "boolean", "IS_FREE", "false"
        }
    }

    /** variantFilter闭包 过滤变体 可以设置忽略那个包 比如这里过滤掉了不在列表中的包*/
    variantFilter { variant ->
        def needed = variant.name in [
                'redFreeRelease',
                'redFreeDebug',
                'redPayRelease',
                'redPayDebug',
                'blueFreeRelease',
                'blueFreeDebug',
                'bluePayRelease',
                'bluePayDebug',
        ]
        setIgnore(!needed)
    }

    /** compileOptions闭包 配置项目使用JDK1.8 */
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    android.applicationVariants.all {
        variant ->
            variant.outputs.all {
                outputFileName = "OkHttp_" + "${defaultConfig.versionName}_${releaseTime()}" + "_${variant.productFlavors[0].name}.apk"
            }
    }

}

static def releaseTime() {
    return new Date().format("yyyyMMdd", TimeZone.getTimeZone("GMT+8"))
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:support-v4:27.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation 'io.reactivex:rxjava:1.3.2'
    implementation 'io.reactivex:rxandroid:1.2.1'
    implementation 'com.squareup.okhttp3:okhttp:3.9.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.6.0'
    implementation 'com.readystatesoftware.systembartint:systembartint:1.0.3'

    implementation 'com.squareup.retrofit2:retrofit:2.7.0'
    implementation 'com.github.bumptech.glide:glide:4.4.0'

    //对应上述多渠道打出的八个包 有不同的八个依赖
    redFreeReleaseImplementation 'com.aaa.bbb.ccc:redFreeRelease:1.1.1'
    redFreeDebugImplementation 'com.aaa.bbb.ccc:redFreeDebug:1.1.1'
    redPayReleaseImplementation 'com.aaa.bbb.ccc:redPayRelease:1.1.1'
    redPayDebugImplementation 'com.aaa.bbb.ccc:redPayDebug:1.1.1'
    blueFreeReleaseImplementation 'com.aaa.bbb.ccc:blueFreeRelease:1.1.1'
    blueFreeDebugImplementation 'com.aaa.bbb.ccc:blueFreeDebug:1.1.1'
    bluePayReleaseImplementation 'com.aaa.bbb.ccc:bluePayRelease:1.1.1'
    bluePayDebugImplementation 'com.aaa.bbb.ccc:bluePayDebug:1.1.1'
}

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值