Gradle特殊用法

ilufei2019發表於2017-07-20

自動調整 *.iml 中 orderEntry 順序

apply plugin: `com.android.application`
android {
    ........
    preBuild {
        doLast {
            def imlFile = file(project.name + ".iml")
            println `Change ` + project.name + `.iml order`
            try {
                def parsedXml = (new XmlParser()).parse(imlFile)
                def jdkNode = parsedXml.component[1].orderEntry.find { it.`@type` == `jdk` }
                parsedXml.component[1].remove(jdkNode)
                def sdkString = "Android API " + android.compileSdkVersion.substring("android-".length()) + " Platform"
                new Node(parsedXml.component[1], `orderEntry`, [`type`: `jdk`, `jdkName`: sdkString, `jdkType`: `Android SDK`])
                groovy.xml.XmlUtil.serialize(parsedXml, new FileOutputStream(imlFile))
            } catch (FileNotFoundException e) {
                // nop, iml not found
            }
        }
    }
    ........
}

如上所示,通過對 *.iml 檔案進行 xml 解析,然後刪除 代表Android SDK 的 jdk 預設節點,並在最後追加 Android SDK 節點。


相關文章