How to remove xml node of AndroidManifest.xml

姜铮
1 min readFeb 1, 2023

Recently, China App Markets have a more strict policy for android app, and it required when you request any sensitive permission, the app should show it privacy policy contract firstly, otherwise, your app mostly will be rejected.

Unfortunately, some permission may bed declared on a library or aar file, you cannot modify it easily, Google has a document to tell us how to remove some node of the AndroidManifest.xml file

but i think we could have another way to do the same things, we can use gradle to deal with the merge progress of AndroidManifest.

project.afterEvaluate {
val variants = android.applicationVariants
variants.all {
outputs.forEach {
it.processManifestProvider.get().doLast {
val file = File(outputs.files.asPath, "AndroidManifest.xml")
if (file.exists().not()) {
return@doLast
}

val builder = DocumentBuilderFactory.newInstance().newDocumentBuilder()
val document = builder.parse(file)
val element = document.documentElement

// remove the permission "android.permission.RECEIVE_BOOT_COMPLETED"
removeMatchedNode(element, "uses-permission", "android:name", "android.permission.RECEIVE_BOOT_COMPLETED")

// remove all action which android:name is "android.intent.action.BOOT_COMPLETED"
removeMatchedNode(element, "action", "android:name", "android.intent.action.BOOT_COMPLETED")

document.xmlStandalone = true
val transformerFactory = TransformerFactory.newInstance()
val transformer = transformerFactory.newTransformer()
transformer.setOutputProperty(javax.xml.transform.OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes")
transformer.transform(DOMSource(document), StreamResult(file))
}
}
}

}

fun removeMatchedNode(element: Element, tagName: String, attributeName: String, attributeValue: String) {
val elementList = element.getElementsByTagName(tagName)
for (i in 0 until elementList.length) {
elementList.item(i)?.let {node ->
val nameAttribute = node.attributes.getNamedItem(attributeName)
if (nameAttribute != null && nameAttribute.nodeValue == attributeValue) {
node.parentNode.removeChild(node)
}
}
}
}

you can remove any node by the method removeMatchedNode()

--

--