I am trying to create a cordova plugin for a custom sdk. This sdk uses bluetooth and has two options to be used.
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?
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);
})
}
});
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With