操作命令
npm install -g plugman //安装plugman
plugman create --name udpPlugin --plugin_id com.whr.plugins.udpPlugin --plugin_version 0.0.1 //创建一个插件项目
cd udpPlugin
plugman platform add --platform_name android
一样插件的原型就搭建好了。
www/udpPlugin.js 说明:
- exec 函数
exec(success, error, "udpPlugin", "coolMethod", [arg0]);
- success: 调用成功 回调函数,
- error: 调用出错 回调函数,
- “udpPlugin”: 插件名称,
- “coolMethod”: 执行插件里的方法,
- [arg0]: 可选参数,执行方法的参数数组。
可以适当修改一下udpPlugin.js
var exec = require('cordova/exec');
var coolMethod = function(arg0, success, error) {
exec(success, error, "udpPlugin", "coolMethod", [arg0]);
};
window.plugins = window.plugins || {};
window.plugins.udpPlugin=coolMethod;
exports.udpPlugin=coolMethod;
不改也可以,在调用的时候就用
cordova.plugins.udpPlugin。。。
形式调用。
其中cordova.plugins.udpPugin是定义在plugin.xml里的,可以修改。
安装插件
到cordova项目里,运行命令:
cordova plugin add ../../udpPlugin
删除
cordova plugin remove com.whr.udpPlugin
使用插件
window.plugins.udpPlugin("some information",
function(data){
console.log(data);
},
function(error){
console.log(error);
});
插件触发事件demo
如果插件里有进行相当耗时的操作,最好用事件的方法异步执行,而不要用callback回调。
在plugin的www/—-.js里定义插件的事件
供java程序调用
module.exports={
HookName : 'myHookName'
}
MyPlugin.prototype.testmethod= function(param) {
var evReceive = document.createEvent('Events');
evReceive.initEvent(this.HookName , true, true);
evReceive.metadata = {
param:param
};
document.dispatchEvent(evReceive);
};
在Java里触发event
final String hook= "cordova.plugins.myPlugin.testmethod('paramvalue');";
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
webView.loadUrl("javascript:" + hook);
}
});
IOS中触发event
NSString *receiveHook;
receiveHook = [NSString stringWithFormat : @"window.tlantic.plugins.socket.receive('%@' );", str];
[self.commandDelegate evalJs : receiveHook];
在前端js里定义handler
var myHandler=function(){
}
在前端js里绑定事件
document.addEventListener(cordova.plugins.myPlugin.HookName , myHandler);
在前端js里移除事件
document.removeEventListener(cordova.plugins.myPlugin.HookName , myHandler);
plugin.xml的一些典型设置
android
js引用名称:
<engines>
<engine name="cordova" version=">=4.0.0" />
</engines>
<js-module src="www/settings.js" name="Settings">
<clobbers target="cordova.plugins.settings" />
</js-module>
ios
<platform name="ios">
<config-file target="config.xml" parent="/*">
<feature name="NativeSettings">
<param name="ios-package" value="NativeSettings"/>
</feature>
</config-file>
<config-file target="*-Info.plist" parent="CFBundleURLTypes">
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLSchemes</key>
<array>
<string>prefs</string>
</array>
</dict>
</array>
</config-file>
<resource-file src="appbeep.wav" />
<header-file src="src/ios/NativeSettings.h" />
<source-file src="src/ios/NativeSettings.m" />
<source-file src="src/ios/lib/libConfiguration.a" framework="true" />
</platform>
配置文件参考文档:
http://cordova.apache.org/docs/en/latest/plugin_ref/spec.html