how to send data or message from java application

2019-07-21 12:31发布

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.

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)

2条回答
走好不送
2楼-- · 2019-07-21 12:32

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);

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; 
}
查看更多
Ridiculous、
3楼-- · 2019-07-21 12:42

If what you need is communication from server to client in asynchronous way than websockets are the solution for you. Exact implementation depends on which web server you use so you'd net to give more details but they all work same way more or less.

查看更多
登录 后发表回答