Cordova插件封装总结

227 阅读2分钟

Android

首先编写一个继承CordovaPlugin类的插件类

public class AppSet extends CordovaPlugin {
    public AppSet(){

    }
}

然后重写它的两个方法

    @Override
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);
    }

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if ("getUserInfo".equals(action)) {
            WXStaticModule staticModule=new WXStaticModule();
            HashMap userInfo=(HashMap) staticModule.getPUserInfo();
            JSONObject res;
            if(userInfo!=null){
                res=new JSONObject(userInfo);
            }else{
                res=new JSONObject("{code:-1,message:'用户信息为空'}");
            }
            callbackContext.success(res);
        }else {
            webView.postMessage(action,args);
        }
        return true;
    }

其中initialize中我们可以对做一些初始化操作。

接下来就是最关键的excute方法,这个方法就是我们接受js调用的方法,其中action是方法名称,args是一个参数数组,callbackContext即回调的上下文对象。

如果我们需要使用Android中的Context对象,那么我们可以使用webview的postMessage方法发送事件到持有webview的activity中,我们可以在对应的activity中进行处理。

    //继承了CordovaActivity的WebPageActivity
    @Override
    public Object onMessage(String id, Object data) {
      //处理js调用
    } 

代码写完我们需要在res下的config.xml中配置一下

 <feature name="AppSet">
     <param name="android-package" value="org.appset.cordova.AppSet" />
  </feature>

原生代码写完需要前端做js端的封装

cordova.define("cordova-plugin-appSet.userInfo", function(require, exports, module) {

var argscheck = require('cordova/argscheck');
var utils = require('cordova/utils');
var exec = require('cordova/exec');
var cordova = require('cordova');
var AppSet=function(){
};

/**
 * Get info
 *
 * @param {Function} successCallback The function to call when the heading data is available
 * @param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL)
 */
AppSet.prototype.getUserInfo = function (successCallback, errorCallback) {
    exec(successCallback, errorCallback, 'AppSet', 'getUserInfo', []);
};
AppSet.prototype.setTitle = function (title,successCallback, errorCallback) {
    exec(successCallback, errorCallback, 'AppSet', 'setTitle', [title]);
};
module.exports = new AppSet();

});

cordova_plugin.js

cordova.define('cordova/plugin_list', function(require, exports, module) {
  module.exports = [
     {
        "id": "cordova-plugin-appSet.userInfo",
        "file": "plugins/cordova-plugin-appset/www/appSet.js",
        "pluginId": "cordova-plugin-appSet",
        "clobbers": [
          "AppSet"
        ]
     },
    "
      ]
    }
});

IOS

在Plugins目录下定义继承CDVPlugin的类即可,声明指定的方法,js端即可调用

@interface CDVAppset : CDVPlugin
{}
+ (NSString*)cordovaVersion;

- (void)getUserInfo:(CDVInvokedUrlCommand*)command;
- (void)setTitle:(CDVInvokedUrlCommand*)command;
- (void)showTitleBar:(CDVInvokedUrlCommand*)command;
- (void)pageDismiss:(CDVInvokedUrlCommand*)command;
@end
@implementation CDVAppset                   
-(void)setTitle:(CDVInvokedUrlCommand*)command
{
    //获取参数的方法
    NSString* title = [command.arguments objectAtIndex:0];
    [self.viewController.navigationItem setTitle:title];
}
- (void)getUserInfo:(CDVInvokedUrlCommand*)command
{
    WXStaticModule *staticModule=[[WXStaticModule alloc] init];
    NSDictionary *dc=[staticModule getPUserInfo];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dc options:0 error:0];
    NSString *dataStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:dataStr];
    //回调触发
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

写完原生代码同样需要在config.xml中添加配置

<feature name="AppSet">
   <param name="ios-package" value="CDVAppset" />
   <param name="onload" value="true" />
</feature>

js端的封装与Android一致。