我是Cordova插件的新手。我想知道是否可以在我的Android插件中创建自定义的android.app.Application?感谢
答案 0 :(得分:4)
可以执行此操作,但您需要在<application>
的{{1}}元素中为应用程序类添加名称引用。
一旦这样做,就是在每次Cordova准备操作后使用AndroidManifest.xml
钩子脚本将其应用于清单。例如:
<强>的plugin.xml 强>
after_prepare
<强> add_application_name.js 强>
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
xmlns:android="http://schemas.android.com/apk/res/android"
id="cordova-plugin-myplugin"
version="1.0.0">
<name>My Plugin</name>
<platform name="android">
<config-file target="config.xml" parent="/*">
<feature name="MyPlugin" >
<param name="android-package" value="my.package.MyPlugin"/>
</feature>
</config-file>
<js-module name="MyPlugin" src="myplugin.js">
<clobbers target="MyPlugin"/>
</js-module>
<source-file src="MyPlugin.java" target-dir="src/my/package" />
<source-file src="MyApplication.java" target-dir="src/my/package" />
<hook type="after_prepare" src="add_application_name.js" />
</platform>
</plugin>
<强> MyApplication.java 强>
#!/usr/bin/env node
module.exports = function(context) {
var APPLICATION_CLASS = "my.package.MyApplication";
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(APPLICATION_CLASS) == -1) {
var result = data.replace(/<application/g, '<application android:name="' + APPLICATION_CLASS + '"');
fs.writeFile(manifestFile, result, 'utf8', function (err) {
if (err) throw new Error('Unable to write into AndroidManifest.xml: ' + err);
})
}
});
}
};