如何使用cordova/phonegap从Java应用程序/插件向javascript发送数据或消息

问题描述:

我想我在这里错过了一些东西.我习惯于将数据从javascript发送到Java,然后通过调用来执行和使用callbackContext方法返回.

I think I'm missing something here. I'm used to sending data from javascript to java and back with calls to execute and back with the callbackContext methods.

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

But if at some points, lets say I have a running thread that needs to send data to the javascript at regular intervals, how should I do that then ? (This assumes that this task is running and has not been triggered by a javascript action, thus no callbackContext is available)

您始终可以通过Java执行javascript,具体操作如下:

You can always execute javascript from java doing this:

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

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

Or you can init the plugin and keep the callback doing this

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

添加了Sephy提供的示例

Added example provided by 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; 
}