Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cordova Plugin customize application class

I am trying to create a cordova plugin for a custom sdk. This sdk uses bluetooth and has two options to be used.

  1. The application class has to extend a class from the sdk so that I can use all features from the sdk.
  2. The application class has to implement a class from the sdk. That is needed to have the bluetooth connection staying alive. And after that I can start the service manually.

I think my problem is that I have to create a custom application class.

Is it possible to do that what I need with a cordova plugin?

like image 410
Peter Avatar asked May 17 '18 19:05

Peter


1 Answers

You can do it like this in your plugin:

plugin.xml:

<platform name="android">
    <source-file src="src/MyPlugin.java" target-dir="src/my/plugin" />
    <source-file src="src/MyApplication.java" target-dir="src/my/plugin" />
</platform>

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

MyApplication.java:

package my.plugin;

import android.app.Application;
import android.util.Log;

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        Log.d("MyApplication", "onCreate");
        super.onCreate();
    }
}

However, I found that the <edit-config> block was prone to problems when the plugin was used in a project with lots of other plugins, so I used a hook script to add the name attribute to the <application> element in AndroidManifest.xml:

In plugin.xml, replace:

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

with:

<hook type="after_prepare" src="hooks/android_app_name.js" />

Then inside your plugin directory create hooks/android_app_name.js:

#!/usr/bin/env node

var APP_CLASS = 'my.plugin.MyApplication';

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

      if (data.indexOf(APP_CLASS) == -1) {
        var result = data.replace(/<application/g, '<application android:name="' + APP_CLASS + '"');
        fs.writeFile(manifestFile, result, 'utf8', function (err) {
          if (err) throw new Error('Unable to write AndroidManifest.xml: ' + err);
        })
      }
    });
  }

};
like image 102
DaveAlden Avatar answered Nov 01 '22 15:11

DaveAlden