从Cordova plugin.xml向AndroidManifest.xml“application”标签添加android:name =“something”

问题描述 投票:18回答:4

我决定打开一个新问题,因为那些已发布的问题都没有,答案很好。

我需要从plugin.xml更新AndroidManifest.xml,以便<application>标记具有以下属性,以及它已有的属性:

android:name="mypackage"

怎么办?

谢谢

android cordova android-manifest cordova-plugins
4个回答
15
投票

我有同样的问题,我使用Cordova钩子来完成这项工作。

首先,编辑你的config.xml文件以添加钩子:

<platform name="android">
    <hook type="after_prepare" src="scripts/android_app_name.js" />
</platform>

创建一个名为scripts/android_app_name.js的文件(设置它可执行文件),在里面,只需使用搜索/替换功能。它应该看起来像:

#!/usr/bin/env node

module.exports = function(context) {

  var fs = context.requireCordovaModule('fs'),
    path = context.requireCordovaModule('path');

  var platformRoot = path.join(context.opts.projectRoot, 'platforms/android');


  var manifestFile = path.join(platformRoot, 'AndroidManifest.xml');

  if (fs.existsSync(manifestFile)) {

    fs.readFile(manifestFile, 'utf8', function (err,data) {
      if (err) {
        throw new Error('Unable to find AndroidManifest.xml: ' + err);
      }

      var appClass = 'YOU_APP_CLASS';

      if (data.indexOf(appClass) == -1) {

        var result = data.replace(/<application/g, '<application android:name="' + appClass + '"');

        fs.writeFile(manifestFile, result, 'utf8', function (err) {
          if (err) throw new Error('Unable to write into AndroidManifest.xml: ' + err);
        })
      }
    });
  }


};

4
投票

事实上,正如jlreymendez所说,正确的方法是:

    <edit-config file="AndroidManifest.xml" target="/manifest/application" mode="merge">
      <application android:name="com.mypackage.MyApplication"/>
    </edit-config>

另请注意,如果删除插件,修改将恢复,钩子技巧不会发生什么。


4
投票

最简单和最新(cordova版本8.1.2)的方式来使用edit-config标签,如下所示:

    <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application">
        <application android:name="mypackage" />
    </edit-config>

以类似的方式,您也可以编辑其他配置。

希望它会有所帮助!


1
投票

我想我和你有同样的问题。我在cordova文档中找到了这个。

https://cordova.apache.org/docs/en/4.0.0/plugin_ref_spec.md.html

如果搜索标题“config-file Element”,你会发现一个例子:

<config-file target="AndroidManifest.xml" parent="/manifest/application">
    <activity android:name="com.foo.Foo" android:label="@string/app_name">
        <intent-filter>
        </intent-filter>
    </activity>
</config-file>
© www.soinside.com 2019 - 2024. All rights reserved.