Cordova插件从本机函数获取异步响应



在我的例子中,我想构建一个简单的插件:

  1. 启动本机页面
  2. (在用户输入内容后(回调到cordova(js(

我没有找到处理回调的方法。我搜索了cordova文档(Echo示例(,第一部分非常简单。但是,它没有提到异步回调。

您可以通过发送一个"无结果";同步响应并保留Cordova回调,以便发送异步结果。例如:

安卓:


public class MyPlugin extends CordovaPlugin {

private static CallbackContext myAsyncCallbackContext = null;
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("myAsyncFunction")) {
// save the callback context
someCallbackContext = myAsyncCallbackContext; 

// Send no result for synchronous callback
PluginResult pluginresult = new PluginResult(PluginResult.Status.NO_RESULT);
pluginresult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginresult);
}
return true;
}

// Some async callback
public void onSomeAsyncResult(String someResult) {
if(myAsyncCallbackContext != null){
// Send async result
myAsyncCallbackContext.success(someResult);
myAsyncCallbackContext = null;
}
}
}

iOS:


@interface MyPlugin : CDVPlugin
- (void)myAsyncFunction:(CDVInvokedUrlCommand *)command;
@end

@implementation MyPlugin
static NSString* myAsyncCallbackId = nil;
- (void)myAsyncFunction:(CDVInvokedUrlCommand *)command {
// save the id
myAsyncCallbackId = command.callbackId;
// Send no result for synchronous callback
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_NO_RESULT];
[pluginResult setKeepCallbackAsBool:YES];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
// Some async callback
- (void) didReceiveSomeAsyncResult:(NSString *)someResult {
if(myAsyncCallbackId != nil){
// Send async result
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:someResult];
[self.commandDelegate sendPluginResult:pluginResult callbackId:myAsyncCallbackId];
myAsyncCallbackId = nil;
}
}
@end

最新更新