Gradle打包动态添加渠道号

一、第一种方法

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.shaw.art"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    buildToolsVersion '28.0.3'
}

//导包
import com.android.build.gradle.api.ApplicationVariant
import groovy.xml.XmlUtil

//动态向AndroidManifest.xml中 添加渠道号
//执行的gradle命令:gradle clean assembleRelease -P channel=1001
project.afterEvaluate {
    android.applicationVariants.each { ApplicationVariant variants ->
        def name = variants.name
        def variantsName = name.capitalize()
        println "nam == ${name}"
        println "capitalizeName == ${variantsName}"
        def mergeManifestTask = project.tasks.getByName("process${variantsName}Manifest")
        println "mergeManifestTask == ${mergeManifestTask}"
        //默认两个task: ':app:Debug' 和  ':app:Release'
        //gradle命令中assembleRelease,所以当执行task ':app:processReleaseManifest'时,才执行下面语句
        mergeManifestTask.doLast { mm ->
            //得到AndroidManifest.xml外部文件夹
            def manifest = mm.manifestOutputDirectory
            println "manifest == ${manifest}"
            //gradle命令中 -P channel=1001,给project设置channel属性,value为1001
            if (project.hasProperty("channel")) {
                addChannel(manifest)
            }
        }
    }
}

def addChannel(File manifest) {
    def channelNo = project.property("channel")
    println "channelNo == ${channelNo}"
    //获取AndroidManifest.xml路径
    def xmlFilePath = manifest.getAbsolutePath()
    def xmlFile = project.file(xmlFilePath+"/AndroidManifest.xml")
    println "xmlFile exists == ${xmlFile.exists()}"
    //调用Groovy解析类
    def parse = new XmlParser().parse(xmlFile)

    println "object == ${parse.application[0]}"
    //添加meta-data标签
    parse.application[0].appendNode("meta-data", ['android:name': 'channel', 'android:value': channelNo])
    xmlFile.withPrintWriter("UTF-8") {
        XmlUtil.serialize(parse, it)
    }
}

dependencies {
    ...
}

二、第二总方法

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.shaw.art"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    buildToolsVersion '28.0.3'
}

//导包
import groovy.xml.*

//动态向AndroidManifest.xml中 添加渠道号
//执行的gradle命令:gradle clean assembleRelease -P channel=1001
project.afterEvaluate {
    def params = gradle.getStartParameter().getProjectProperties()
    def file = new File(rootProject.getRootDir().getAbsolutePath() + "/app/src/main/AndroidManifest.xml")

    def manifest = new XmlParser().parse(file)
    def printWriter = new PrintWriter(file)

    def android = new Namespace('http://schemas.android.com/apk/res/android', 'android')
    def channelData = ["android:name": "channel", "android:value": params.get("channel")]
    println "channelData == ${channelData}"

    def metaNodeList = manifest.application["meta-data"]
    def existedChannelNode = null

    if (params.get("channel")) {
        metaNodeList.each {
            def name = it.attribute(android.name)
            println "name == ${name}"

            if (name == 'channel') {
                existedChannelNode = it
            }
        }
        if (!existedChannelNode) {
            manifest.application[0].appendNode("meta-data", channelData)
        } else {
            existedChannelNode.attributes().put(android.value, params.get("channel"))
        }
    }

    XmlUtil.serialize(manifest, printWriter)
}

dependencies {
   ...
}

参考:
https://www.jianshu.com/p/c3161a20ac44
https://blog.csdn.net/qq_33453910/article/details/80904366

你可能感兴趣的:(Gradle打包动态添加渠道号)