Add android:name="something" to AndroidManifest.xml "application" tag from Cordova plugin.xml

user2548436 picture user2548436 · Dec 18, 2014 · Viewed 9.3k times · Source

I decided to open new question because none of those that are already posted, has a good answer.

I need to update AndroidManifest.xml "from plugin.xml", so that the <application> tag has the following property, alongside those it already has:

android:name="mypackage"

How can do that?

Thank you

Answer

ndeverge picture ndeverge · Sep 4, 2015

I had the same issue, and I used a Cordova hook to do the work.

First, edit your config.xml file to add the hook:

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

Create a file called scripts/android_app_name.js (set it executable), and inside, just use a search/replace function. It should look like:

#!/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);
        })
      }
    });
  }


};