Android - 如何避免多个清单文件中的重复?

Android - How to avoid repetition in multiple Manifest files?

我的项目有 3 个清单文件:

flavour/AndroidManifest.xml
flavourDebug/AndroidManifest.xml
flavourRelease/AndroidManifest.xml

这里是flavour/AndroidManifest.xml:

<manifest
    xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.READ_CONTACTS" />
</manifest>

这里是flavourDebug/AndroidManifest.xml:

<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application android:name="com.domain.android.MyApplication"
        android:allowBackup="false"
        android:label="@string/app_name"
        android:logo="@drawable/ic_logo"
        android:theme="@style/Theme.CustomActionBarStyle"
        android:networkSecurityConfig="@xml/network_security_config"
        tools:replace="theme">

        // Activity definitions in here

     </application>
</manifest>

这里是flavourRelease/AndroidManifest.xml:

<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application android:name="com.domain.android.MyApplication"
        android:allowBackup="false"
        android:label="@string/app_name"
        android:logo="@drawable/ic_logo"
        android:theme="@style/Theme.CustomActionBarStyle"
        tools:replace="theme">

        // Activity definitions in here (these are the EXACT SAME as the ones in flavourDebug/AndroidManifest.xml)

     </application>
</manifest>

如您所见,调试清单和发布清单之间的唯一区别是缺少发布清单 android:networkSecurityConfig

此外,// Activity definitions in here部分完全相同。我想要的是避免 Activity 重复。每次我们必须更改 Activity 定义中的某些内容(或添加新的 Activity)时,我们必须在 2 个清单文件(调试和发布)中进行更改。

我想到了将所有内容都放在 AndroidManifest.xml 主文件中。问题是我无法将 android:networkSecurityConfig="@xml/network_security_config" 仅添加到调试版本 .

在 Android 布局中,该问题已通过 <include> 标签解决。不幸的是,清单中没有。

如何解决这个重复问题?

您当然可以控制如何合并资源,并且可以使用主文件夹避免此类重复,查看文档 here,您可能会对 tools:node="merge" 感兴趣,它可以帮助您控制节点的方式合并后,您将从上面的 link 获得更多信息。

您绝对可以将公共部分放在 flavour/AndroidManifest.xml 中,将附加属性放在 flavourDebug/AndroidManifest.xml 中(以及 src/flavourDebug/res/xml 目录中引用的 xml 文件):

<application
    android:networkSecurityConfig="@xml/network_security_config" />

添加属性时,它应该开箱即用,无需调整合并规则(tools:node="merge" 是大多数元素的默认行为)。

使用 Android Studio 3.1(可能还有更早的版本),您可以在 Merged manifest 选项卡中查看最终清单,以及每个属性或元素的来源编辑的。