多渠道打包gradle方式(解决类似'360'纯数字渠道名)

    1、AndroidManifest.xml文件中定义一个CHANNEL_NAME,打包的时候、这个值会用自己设定的渠道号替换
    
        //在java代码中读取meta-data
        /*ApplicationInfo appInfo = this.getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
            String channel=appInfo.metaData.get("CHANNEL_NAME")+"";*/

    2、build.gradle配置
    defaultConfig {
        manifestPlaceholders = [CHANNEL_VALUE: "2000"]//这里2000是默认值
    }    
    productFlavors {//设置不同的渠道值
        xiaomi{
            manifestPlaceholders = [MACHAT_CHANNEL_VALUE:'2001']
        }
        baidu{
            manifestPlaceholders = [MACHAT_CHANNEL_VALUE:"2002"]
        }
        huawei {
            manifestPlaceholders = [MACHAT_CHANNEL_VALUE:"2003"]
        }
        yingyongbao {
            manifestPlaceholders = [MACHAT_CHANNEL_VALUE:"2004"]
        }
   }  
   //定制生成的apk的名字 ${defaultConfig.versionName}  
   applicationVariants.all { variant ->
    variant.outputs.each { output ->
        def outputFile = output.outputFile
        if (outputFile != null && outputFile.name.endsWith('.apk')) {
                def fileName = 
                outputFile.name.replace(".apk", "-${defaultConfig.versionName}-"+releaseTime()
                +".apk")//
            output.outputFile = new File(outputFile.parent, fileName)
        }
    }
    //这样得到的名字是test-xiaomi-release-1.4.2-201802061701.apk
}
def releaseTime() {//打包时间
    return new Date().format("yyyyMMddHHmm", TimeZone.getDefault())
}
3、另外还有一种配置方式,这和方式2是等价的
defaultConfig {
        manifestPlaceholders = [CHANNEL_VALUE: "2000"]//这里2000是默认值
} 
productFlavors {
    "2001"{}
   "2002"{}
   "2003"{}
   "2004"{}
}
productFlavors.all { flavor ->
    flavor.manifestPlaceholders = [CHANNEL_VALUE: name]
}
       //定制生成的apk的名字 ${defaultConfig.versionName}  
   applicationVariants.all { variant ->
    variant.outputs.each { output ->
        def outputFile = output.outputFile
        if (outputFile != null && outputFile.name.endsWith('.apk')) {
                def fileName = 
                outputFile.name.replace(".apk", "-${defaultConfig.versionName}-"+releaseTime()
                +".apk")//
            output.outputFile = new File(outputFile.parent, fileName)
        }
    }
    //这样得到的名字是test-2001-release-1.4.2-201802061701.apk

studio 3.0以上的配置

    /*默认为2000
    小米 2001
    百度开发者平台 2002
    华为 2003
    应用宝 2004*/

    flavorDimensions "default"
    productFlavors {
        '2001' { dimension "default" }
        "2002" {dimension "default"}
        "2003" {dimension "default"}
        "2004" { dimension "default" }
    }

    productFlavors.all {
        flavor -> flavor.manifestPlaceholders = [CHANNEL_VALUE: name]
    }

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

你可能感兴趣的:(Android,Android,Studio)