我想我在这里遗漏了一些东西。我习惯于通过调用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/