简体   繁体   中英

how can I add attribute to the android activity 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 the activity to be like this:

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

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

Any help please ?

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

The config-file element only allows you to append new children to an XML document tree.

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

It looks like hooks are the way to do it. I did this in a way similar to that suggested in https://stackoverflow.com/a/32394342/2569560

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 append the 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);
        })
      }
    });
  }


};

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM