Cordova:将插件中的数据发送回CordovaView的最佳方法是什么?

时间:2012-10-31 10:41:46

标签: plugins cordova

我需要将数据/对象从Cordova插件发送回主Cordova View。这是为了改变ActionBar标题等等。

要走的路是什么?

2 个答案:

答案 0 :(得分:1)

返回PluginResult是可接受的方法。将使用您通过PluginResult发回的数据调用方法的成功回调。

答案 1 :(得分:0)

我已经编写了工作代码,以将数据从Cordova发送到CordovaPlugin,反之亦然。

Android代码

public class CustomPlugin extends CordovaPlugin {
  @Override
  public boolean execute(String action, JSONArray args, CallbackContext             callbackContext) throws JSONException {

    Log.d(TAG, action); //doPluginAction is printed
    Log.d(TAG, args.getString(0));//parameter is printed

    PluginResult result = new PluginResult(PluginResult.Status.OK, "here you can also send you message to app from plugin"); // You can send data, String, int, array, dictionary and etc
    result.setKeepCallback(false);
    callbackContext.sendPluginResult(result);

    return true;
  }
}

iOS代码

//CustomPlugin.h file
#import <Cordova/CDVPlugin.h>
#import <Foundation/Foundation.h>

@interface CustomPlugin : CDVPlugin
-(void) doPluginAction:(CDVInvokedUrlCommand*) command;
@end

//CustomPlugin.m file
#import "CustomPlugin.h"
@implementation CustomPlugin
-(void) doPluginAction:(CDVInvokedUrlCommand*) command {
    CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:"here you can also send you message to app from plugin"];// You can send data, String, int, array, dictionary and etc
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
@end

插件js文件的代码

www/CustomPlugin.js
var exec = require('cordova/exec');
exports.callPluginMethod = function (parameter, success, error) {
    exec(success, error, “CustomPlugin”, "doPluginAction", [parameter]);
};

呼叫插件和完成块处理:

cordova.plugins.CustomPlugin.callPluginMethod("parameter", (success: any) => {
    console.log(success);
},
(error:any) => {
    console.log(error);
})