Cordova插件:向Java发送事件吗? [英] Cordova Plugin: Send event to Javascript?

查看:68
本文介绍了Cordova插件:向Java发送事件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按照此处找到的教程开发适用于Android的Cordova插件: http://www.mat-d.com/site/tutorial-creating-a-cordova-phonegap-plugin-for-android-app/

I'm trying to develop a Cordova plugin for Android following the tutorial found here: http://www.mat-d.com/site/tutorial-creating-a-cordova-phonegap-plugin-for-android-app/

到目前为止,很好。但是,我想知道如何通过插件的Javascript代码发送数据/触发事件-例如,当用户点击本机代码中的图标时,我希望Javascript执行某些操作。这可能吗?

So far, so good. However, I'd like to know how to send data/trigger an event in my Javascript code from my plugin - for example, when a user taps an icon in my native code, I'd like my javascript to do something. Is this possible?

推荐答案

所以我按如下方式工作:

So I got it to work as follows:

I在我的插件中创建了一个私人CallbackContext对象:

I created a private CallbackContext object in my plugin:

private CallbackContext callbackContext;

并将CallbackContext存储在execute()方法中:

and stored the CallbackContext supplied in the execute() method in it:

public boolean execute(final String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    this.callbackContext = callbackContext;
}

在Java代码的其他地方,我可以访问此回调并将插件结果发送到它。但是,此回调在第一次触发后将变为无效,除非将keepCallback设置为 true

Elsewhere in my Java code, I can access this callback and send plugin results to it. This callback will become invalid, however, after it's first triggered, unless keepCallback is set to true:

PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, "WHAT");
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);

这使我成为一个快乐的露营者。我希望它可以帮助其他人!

This made me a happy camper. I hope it helps someone else!

这篇关于Cordova插件:向Java发送事件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆