How can I add android activity attribute from plugin.xml in cordova?

I have my Activity in AndroidManifest.xml:

    <activity android:name="mobile_app" >
    </activity>

      

I want to add an attribute to an activity like this:

    <activity android:name="mobile_app" android:launchMode="singleInstance" >
    </activity>

      

I know I can add the attribute directly in the androidManifest.xml file, but it works, but I want my plugin to add the attribute to the activity tag.

Any help please?

+3


source to share


3 answers


Add this to your plugin.xml for your android platform element:



<platform name="android">
    <config-file target="AndroidManifest.xml" parent="/manifest/application">
        <activity android:name="mobile_app" android:launchMode="singleInstance" />
    </config-file>
</platform>

      

+1


source


I need to do this too, but it looks like it's not possible:



The config-file element allows you to add new child elements to the XML document tree.

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

+1


source


It looks like hooks are the way to do it. I did it the way suggested at fooobar.com/questions/355798 / ...

In config.xml, inside <platform name="android">

, add

<hook type="after_build" src="scripts/androidMainActivityAttributeAdd.js" />

      

Then add a script called androidMainActivityAttributeAdd.js

. Here you add an attribute inside the activity tag.

#!/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 attribute = 'android:launchMode="singleInstance"';

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

        var result = data.replace(/android:name="MainActivity"/g, 'android:name="MainActivity" ' + attribute);

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


};

      

+1


source







All Articles