Android12升级

工作需要升级到编译版本31 在这里记录一下遇到的问题。

错误:Manifest merger failedManifest merger failed 这个问题通常搜到的答案是manifest文件格式错误,但这是由于升级编译版本的原因,在Android SDK 31中,需要明确声明组件的 exported属性 android:exported="true" 官方文档如下:



这意味这我们的manifest中每个组件的字段都需要添加exported的属性,包括所有依赖的库和module,主工程和module可以自己修改,但如果依赖的库没有写规范,结果会编译成功后在Android12版本上不能正确安装,而远程依赖的库和插件是不好修改的。此时要用到Android构建特性,Android在打包过程中,所有的组件和依赖产生的manifest文件将集合到一起,同时主manifest即我们app的manifest文件将会被重写,所以可以用gradle文件Groovy脚本实现。

具体在GitHub上有实现,笔者在此只是转载:https://github.com/phamtdat/AndroidSnippets/blob/master/Android12AndroidManifestAddMissingAndroidExported/build.gradle

具体代码如下:

import org.w3c.dom.Element
import org.w3c.dom.Node import javax.xml.transform.dom.DOMSource
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.TransformerFactory
import javax.xml.transform.Transformer def addAndroidExportedIfNecessary(File manifestFile) {
def manifestAltered = false
def reader = manifestFile.newReader()
def document = groovy.xml.DOMBuilder.parse(reader)
def application = document.getElementsByTagName("application").item(0)
if (application != null) {
println "Searching for activities, services and receivers with intent filters..."
application.childNodes.each { child ->
def childNodeName = child.nodeName
if (childNodeName == "activity" || childNodeName == "activity-alias" ||
childNodeName == "service" || childNodeName == "receiver") {
def attributes = child.getAttributes()
if (attributes.getNamedItem("android:exported") == null) {
def intentFilters = child.childNodes.findAll {
it.nodeName == "intent-filter"
}
if (intentFilters.size() > 0) {
println "found ${childNodeName} ${attributes.getNamedItem("android:name").nodeValue} " +
"with intent filters but without android:exported attribute" def exportedAttrAdded = false
for (def i = 0; i < intentFilters.size(); i++) {
def intentFilter = intentFilters[i]
def actions = intentFilter.childNodes.findAll {
it.nodeName == "action"
}
for (def j = 0; j < actions.size(); j++) {
def action = actions[j]
def actionName = action.getAttributes().getNamedItem("android:name").nodeValue
if (actionName == "com.google.firebase.MESSAGING_EVENT") {
println "adding exported=false to ${attributes.getNamedItem("android:name")}..."
((Element) child).setAttribute("android:exported", "false")
manifestAltered = true
exportedAttrAdded = true
}
}
}
if (!exportedAttrAdded) {
println "adding exported=true to ${attributes.getNamedItem("android:name")}..."
((Element) child).setAttribute("android:exported", "true")
manifestAltered = true
}
}
}
}
}
}
if (manifestAltered) {
document.setXmlStandalone(true)
Transformer transformer = TransformerFactory.newInstance().newTransformer()
DOMSource source = new DOMSource(document)
FileWriter writer = new FileWriter(manifestFile)
StreamResult result = new StreamResult(writer)
transformer.transform(source, result)
println "Done adding missing android:exported attributes to your AndroidManifest.xml. You may want to" +
"additionally prettify it in Android Studio using [command + option + L](mac) or [CTRL+ALT+L](windows)."
} else {
println "Hooray, your AndroidManifest.xml did not need any change."
}
} def getMissingAndroidExportedComponents(File manifestFile) {
List<Node> nodesFromDependencies = new ArrayList<>()
def reader = manifestFile.newReader()
def document = groovy.xml.DOMBuilder.parse(reader)
def application = document.getElementsByTagName("application").item(0)
if (application != null) {
println "Searching for activities, services and receivers with intent filters..."
application.childNodes.each { child ->
def childNodeName = child.nodeName
if (childNodeName == "activity" || childNodeName == "activity-alias" ||
childNodeName == "service" || childNodeName == "receiver") {
def attributes = child.getAttributes()
if (attributes.getNamedItem("android:exported") == null) {
def intentFilters = child.childNodes.findAll {
it.nodeName == "intent-filter"
}
if (intentFilters.size() > 0) {
println "found ${childNodeName} ${attributes.getNamedItem("android:name").nodeValue} " +
"with intent filters but without android:exported attribute" def exportedAttrAdded = false
for (def i = 0; i < intentFilters.size(); i++) {
def intentFilter = intentFilters[i]
def actions = intentFilter.childNodes.findAll {
it.nodeName == "action"
}
for (def j = 0; j < actions.size(); j++) {
def action = actions[j]
def actionName = action.getAttributes().getNamedItem("android:name").nodeValue
if (actionName == "com.google.firebase.MESSAGING_EVENT") {
println "adding exported=false to ${attributes.getNamedItem("android:name")}..."
((Element) child).setAttribute("android:exported", "false")
exportedAttrAdded = true
}
}
}
if (!exportedAttrAdded) {
println "adding exported=true to ${attributes.getNamedItem("android:name")}..."
((Element) child).setAttribute("android:exported", "true")
}
nodesFromDependencies.add(child)
}
}
}
}
}
return nodesFromDependencies
} def addManifestFileComponents(File manifestFile, List<Node> components) {
def reader = manifestFile.newReader()
def document = groovy.xml.DOMBuilder.parse(reader)
def application = document.getElementsByTagName("application").item(0)
if (application != null) {
println "Adding missing components with android:exported attribute to ${manifestFile.absolutePath} ..."
components.each { node ->
Node importedNode = document.importNode(node, true)
application.appendChild(importedNode)
}
}
if (components.size() > 0) {
document.setXmlStandalone(true)
Transformer transformer = TransformerFactory.newInstance().newTransformer()
DOMSource source = new DOMSource(document)
FileWriter writer = new FileWriter(manifestFile)
StreamResult result = new StreamResult(writer)
transformer.transform(source, result)
println "Added missing app-dependencies components with android:exported attributes to your " +
"AndroidManifest.xml.You may want to additionally prettify it in Android Studio using " +
"[command + option + L](mac) or [CTRL+ALT+L](windows)."
}
println "----"
} task doAddAndroidExportedIfNecessary {
doLast {
def root = new File(project.rootDir, "")
if (root.isDirectory()) {
def children = root.listFiles()
for (def i = 0; i < children.size(); i++) {
File child = children[i]
if (child.isDirectory()) {
File srcDirectory = new File(child, "src")
if (srcDirectory.exists() && srcDirectory.isDirectory()) {
def srcChildren = srcDirectory.listFiles()
for (def j = 0; j < srcChildren.size(); j++) {
File manifestFile = new File(srcChildren[j], "AndroidManifest.xml")
if (manifestFile.exists() && manifestFile.isFile()) {
println "found manifest file: ${manifestFile.absolutePath}"
addAndroidExportedIfNecessary(manifestFile)
println "-----"
}
}
}
}
}
}
}
} task doAddAndroidExportedForDependencies {
doLast {
List<Node> missingComponents = new ArrayList<>()
def root = new File(project.rootDir, "")
if (root.isDirectory()) {
def children = root.listFiles()
for (def i = 0; i < children.size(); i++) {
File child = children[i]
if (child.isDirectory()) {
File mergedManifestsDirectory = new File(child, "build/intermediates/merged_manifests")
if (mergedManifestsDirectory.exists() && mergedManifestsDirectory.isDirectory()) {
def manifestFiles = mergedManifestsDirectory.listFiles().findAll { directoryChild ->
directoryChild.isDirectory() &&
(new File(directoryChild, "AndroidManifest.xml")).exists()
}.stream().map { directoryWithManifest ->
new File(directoryWithManifest, "AndroidManifest.xml")
}.toArray() if (manifestFiles.size() > 0) {
File mergedManifest = manifestFiles[0]
if (mergedManifest.exists() && mergedManifest.isFile()) {
missingComponents = getMissingAndroidExportedComponents(mergedManifest) if (missingComponents.size() > 0) {
File srcDirectory = new File(child, "src")
if (srcDirectory.exists() && srcDirectory.isDirectory()) {
def srcChildren = srcDirectory.listFiles()
for (def j = 0; j < srcChildren.size(); j++) {
File manifestFile = new File(srcChildren[j], "AndroidManifest.xml")
if (manifestFile.exists() && manifestFile.isFile()) {
addManifestFileComponents(manifestFile, missingComponents)
}
}
}
}
}
}
}
}
}
}
}
}

具体使用方法将此代码加入app中的gradle中,也可以抽出为独立gradle文件,在build后执行doAddAndroidExportedIfNecessary 任务,如果成功后会在app中的manifest文件中找到遍历出来未明确表明的exported得组件声明。

如果失败的话可以尝试将SDK版本降到30在执行构建任务再提高编译版本。之后就可以开启12的特新测试了。在此感谢提供脚本的大佬。

Android 开发进程 0.35 升级编译版本Android12的更多相关文章

  1. Android开发进程0.1 轮播图 Scrollview Fragment

    轮播图的实现 轮播图通过banner可以较为便捷的实现 1.添加本地依赖,在dependence中搜索相关依赖 2.添加banner的view组件 3.创建适配器GlideImageLoader ex ...

  2. Android开发学习总结(一)——搭建最新版本的Android开发环境

    Android开发学习总结(一)——搭建最新版本的Android开发环境(转) 最近由于工作中要负责开发一款Android的App,之前都是做JavaWeb的开发,Android开发虽然有所了解,但是 ...

  3. Qt for Windows:Qt 5.4.0 MinGW 静态编译版本制作 (转)

    大致流程: 1.安装Qt(源码版)以及其他必要的环境 2.编译/安装 3.配置 4.使用 ----------正文分割线---------- 1.安装Qt(源码版) 1.1 下载Qt(两个地址二选一即 ...

  4. 转:Android开发实践:用脚本编译Android工程

    转自: http://ticktick.blog.51cto.com/823160/1365947 一般情况下,我们都是使用Eclipse+ADT插件或者Android studio软件来编译Andr ...

  5. android开发--数据库(更新或者降低版本)

    Andoird的SQLiteOpenHelper类中有一个onUpgrade方法. 1. 帮助文档里说的"数据库升级"是指什么? 你开发了一个应用,当前是1.0版本.该程序用到了数 ...

  6. 【转】Android开发学习总结(一)——搭建最新版本的Android开发环境

    最近由于工作中要负责开发一款Android的App,之前都是做JavaWeb的开发,Android开发虽然有所了解,但是一直没有搭建开发环境去学习,Android的更新速度比较快了,Android1. ...

  7. Android开发指南--0 总览

    无意间发现一个网站,主打IOS方面的教程,然而作为一个Android开发者,我就找了下网站里有没有Android的教程,还真有,这里就翻译一下. 翻译目标教程:https://www.raywende ...

  8. android开发(0):android studio的下载安装与简单使用 | sdk的安装与编译运行

    android studio,简称AS,是集成开发环境,所谓集成,就是集编辑.编译.调试.打包等于一体.简单来说,通过AS,就可以开发出在android系统上运行的APP. 我使用的是macos系统. ...

  9. Android 开发 8.0版本启动Service的方法

    前言  google在更新Android8.0后对Service的权限越发收紧.导致目前想要启动服务必需实现服务的前台化(否则在服务启动5秒后,系统将自动报错).下面我们就来看看如何在8.0上启动服务 ...

随机推荐

  1. Linux初探之如何查看帮助文档自学命令

    linux命令种类繁多,参数各异,要每个都记住除非是过目不忘的神人,否则你只能记住常用的那几个,等到 要用时还是得靠--help,man,info这些命令去读文档,可是这些文档看起来也不那么直观,所以 ...

  2. 读vue-cli3 官方文档的一些学习记录

    原来一直以为vue@cli3 就是创建模板的工具,读了官方文档才知道原来这么有用,不少配置让我长见识了 Prefetch 懒加载配置 懒加载相信大家都是知道的,使用Import() 语法就可以在需要的 ...

  3. vue+vant实现购物车的全选和反选业务,带你研究购物车的那些细节!

    前言 喜欢购物的小伙伴看过来,你们期待已久的购物车来啦!相信小伙伴逛淘宝时最擅长的就是加入购物车了,那购物车是如何实现商品全选反选的呢?今天就带你们研究购物车的源码,以vue+vant为例. 正文 首 ...

  4. AI 常见术语总结

      BN(Batch-normalization)在一层的输出上计算所有特征映射的均值和标准差,并且使用这些值规范化它们的响应.因此使得所有神经图(neural maps)在同样范围有响应,而且是零均 ...

  5. MySQL存储结构及SQL分类

    MySQL目录结构 bin -- mysql执行程序 docs -- 文档 share - 各国编码信息 data -- 存放mysql 数据文件 * 每个数据库 创建一个同名文件夹,.frm 存放t ...

  6. 源码解析Spring AOP的加载与生效

    本次博主主要进行Spring AOP这里的解析,因为在工作中使用后,却不知道背后的实现原理并在使用的过程中发现了一些认知缺陷,所以决定写这么一篇文章以供大家参考参考,进入正题. 本次博主使用了@Asp ...

  7. 根据短链生成二维码并上传七牛云(Java)

    通过短链生成二维码并上传七牛云(Java) 前言 网上这种帖子其实也是很多,大部分搜出来的是CSDN的,然后点进去一看都几乎一样:所以这次给个自己实践的例子记录. 这次也是通过搜索得到的一部分能实现这 ...

  8. linux网络编程(一)

    ============================================================== 第一天:基本概念.TCP.FTP: =================== ...

  9. CSS003. 盒子水平垂直居中简写属性(place-items)

    place-items  CSS 中的 place-items 是一个简写属性 ,它允许你在相关的布局(如 Grid 或 Flexbox)中可以同时沿着块级和内联方向对齐元素 (例如:align-it ...

  10. 使用Redis Stream来做消息队列和在Asp.Net Core中的实现

    写在前面 我一直以来使用redis的时候,很多低烈度需求(并发要求不是很高)需要用到消息队列的时候,在项目本身已经使用了Redis的情况下都想直接用Redis来做消息队列,而不想引入新的服务,kafk ...