Android笔记(十六):Gradle脚本动态修改AndroidManifest.xml的MainActivity

在主模块build.gradle添加如下代码即可修改AndroidManifest.xml的MainActivity,sync项目的时候就会执行

原理:利用Groovy XmlSlurper来改写xml文件

import groovy.xml.XmlUtil

this.afterEvaluate {
    def manifestFile = "${projectDir}/src/main/AndroidManifest.xml
    def xml = file(manifestFile)
    def manifest = new XmlSlurper().parse(manifestFile)
    def application = manifest.application

    application.activity.each {
        def isFind = false
        it.children().each {
            if(it.name() == "intent-filter"){
                it.children().each{
                    if(it.name()=="action" &&
 it.@"android:name"=="android.intent.action.MAIN"){
                        isFind = true
                        return true
                    }
                }

            }
            if(isFind){
                return  true
            }
        }

        if (isFind){
            it.@"android:name" = "New Activity"
            return true
        }
    }

    xml.withWriter {out->
        XmlUtil.serialize(manifest, out)
    }
}

注:

${projectDir} :build.gradle的路径

isFind:标志是否找到MainActivity所在的activity节点

XmlUtil.serialize:保存修改后的xml文件

猜你喜欢

转载自blog.csdn.net/weixin_40855673/article/details/108977416