美文网首页
动态修改合并后的Manifest文件

动态修改合并后的Manifest文件

作者: _Ryan | 来源:发表于2017-12-07 19:28 被阅读566次

    APK文件只能包含一个AndroidManifest.xml文件,但是Android Studio项目可以包含多个Manifest文件,因此在构建应用时,Gradle构建会将所有的清单文件合并到一个封装到APK文件的清单文件中。所有我们的主项目的Manifest文件并不是最终的打包时的Manifest文件

    假如我们引入一个第三方库,但是里面的Mianfest文件定义了一些我们不想要的东西,在合并到最终的Manifest文件时我们需要删除里面的一些东西(多余的权限申请,多余的Activity定义等),我们可以参考一下合并多个清单文件的规则:合并多个清单文件 利用清单文件的合并规则去删除或者添加一些属性

    还有另一种方法就是在Gradle构建的过程中通过Task去修改Manifest文件
    Migrate to Android Plugin for Gradle 3.0.0 这篇文章中介绍了一种方法,通过Android Plugin提供的task拿到Manifest的内容,然后对其做修改 如下:

    android.applicationVariants.all { variant ->
        variant.outputs.all { output ->
            output.processManifest.doLast {
                // Stores the path to the maifest.
                String manifestPath = "$manifestOutputDirectory/AndroidManifest.xml"
                // Stores the contents of the manifest.
                def manifestContent = file(manifestPath).getText()
                // Changes the version code in the stored text.
                manifestContent = manifestContent.replace('android:versionCode="1"',
                        String.format('android:versionCode="%s"', generatedCode))
                // Overwrites the manifest with the new text.
                file(manifestPath).write(manifestContent)
            }
        }
    }
    

    但是上面的方法的给的有瑕疵:
    variant.outputs返回的是一个List,并没有all方法,应该换用each方法(应该是文档的错误)
    Manifest文件的位置可以直接通过output来拿到

    android.applicationVariants.all { variant ->
        variant.outputs.each { output ->
            output.processManifest.doLast {
                def manifestOutFile = output.processManifest.manifestOutputFile
                def manifestContent = manifestOutFile.getText('UTF-8')
                ···
                //对manifestContent进行字符串操作
                ···
                manifestOutFile.write(manifestContent)
            }
        }
    }
    

    可以通过manifestOutputFile.path确定最终Manifest文件的位置
    全量编译时


    image.png

    相关文章

      网友评论

          本文标题:动态修改合并后的Manifest文件

          本文链接:https://www.haomeiwen.com/subject/ohlkixtx.html