cordova - 如何使用 cordova/phonegap 将数据或消息从 java 应用程序/插件发送到 javascript

标签 cordova phonegap-plugins cordova-plugins

我想我在这里遗漏了一些东西。我习惯于通过调用execute 和callbackContext 方法将数据从javascript 发送到java 并返回。

但如果在某些时候,假设我有一个正在运行的线程需要定期向 JavaScript 发送数据,那么我应该怎么做呢? (这假设该任务正在运行并且尚未由 javascript 操作触发,因此没有可用的callbackContext)

最佳答案

您始终可以通过 java 执行 javascript:

String js = "alert('test')";
webView.loadUrlNow("javascript:" + js);

或者您可以初始化插件并保持回调执行此操作

PluginResult pgRes = new PluginResult(PluginResult.Status.OK, "message");
pgRes.setKeepCallback(true);
callbackContext.sendPluginResult(pgRes);

添加了Sephy提供的示例

private String myCbkId;
// Store callbackId from a call to execute 
@Override public boolean execute(String action, JSONArray arr, CallbackContext cbkCtx) throws JSONException { 

    myCbkId = cbkCtx.getCallbackId(); 
    JSONObject data = arr.getJSONObject(0); 
    String ack = data.getString("data"); // You can acknowledge to the callback for instance and keep it alive 
    Log.d(TAG, "ack".equals(ack) ? "ack !" : "not ack !");

    // These lines can be reused anywhere in your app to send data to the javascript
    PluginResult result = new PluginResult(PluginResult.Status.OK, ack);
    result.setKeepCallback(true);//This is the important part that allows executing the callback more than once, change to false if you want the callbacks to stop firing  
    this.webView.sendPluginResult(result, this.myCbkId); 

    return true; 
}

关于cordova - 如何使用 cordova/phonegap 将数据或消息从 java 应用程序/插件发送到 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27219376/

相关文章:

cordova - cordova/phonegap 中 ChildBrowser 和 InAppBrowser 的区别

ios - cordova 3.4.0 使用 paypal 插件

ios - iOS 的 Cordova 应用程序构建失败 ** 存档失败 **

android - 找不到 com.parse.bolts :bolts-android:1. 1.2。在手机差距项目(android studio)中?

javascript - 如何在 ionic 项目中使用自定义 cordova 插件?

windows - Cordova 窗口错误 : "cordova/windows8/commandProxy" not found

javascript - 退出javascript中的回调方法

android - 检测 phonegap webview 何时完成加载 android

android - 无法读取未定义的属性 'getPicture' - ionic 相机

iphone - 在 Phonegap + IOS 按钮中使用 iScroll 4 多次触发点击事件