如何将 xmlns(XML 命名空间)添加到 android 清单 header

how to add xmlns (XML namespaces) to android manifest header

我用的是ionic框架,我用过

        <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
            <application android:allowBackup="false" tools:replace="android:allowBackup" />
            <application android:fullBackupOnly="false" />
        </edit-config>

避免 android 应用中的备份服务。

我在 config.xml 中添加了它,它会自动添加到清单中,但是 xmlns: tools="http://schemas.android.com/tools" 需要手动添加到清单中,否则构建会失败并引发错误:

The prefix "tools" for attribute "tools: replace" associated with an element type "application" is not bound.

有什么方法可以将 xmlns 从配置文件自动添加到 android 清单中?

您可以使用挂钩脚本来添加命名空间。例如,在您的 Cordova 项目中创建 hooks/add_tools_namespace.js:

#!/usr/bin/env node

const fs = require('fs'),
    path = require('path');

module.exports = function (context) {
    const toolsAttribute = "xmlns:tools=\"http://schemas.android.com/tools\"";
    const manifestOpen = "<manifest";

    const manifestPath = path.join(context.opts.projectRoot, 'platforms/android/app/src/main/AndroidManifest.xml');
    let manifest = fs.readFileSync(manifestPath).toString();

    if(manifest.indexOf(toolsAttribute) == -1) {
        manifest = manifest.replace(manifestOpen, manifestOpen + " " + toolsAttribute + " ");
        fs.writeFileSync(manifestPath, manifest, 'utf8');
    }
};

然后从您的 config.xml:

引用它
<platform name="android">
    ...
    <hook type="after_prepare" src="hooks/add_tools_namespace.js" />
</platform>