我如何在Android的WebView中的JavaScript,Java的通信同步? [英] How do I make JavaScript-Java communication sync in Android WebView?
问题描述
我已经得到的WebView,JS $里面C $℃。我也有接口,允许的WebView到Java code Java方法调用。 我需要从JS传递数据到Java :要做到这一点:
I've got WebView, JS code inside it. Also I have interface to allow Java method invocation from WebView to Java code. I need to pass data from JS to Java. To do so:
webView.loadUrl("javascript:getData()");
//Obtain Java object here
在JavaScript的:
In JavaScript:
function gataData () {
//serialize data to JSON, pass it as 'native' function param
JSInterface.setLocationsData(data);// This calls a Java function setLocationsData(String param)
}
在JavaScript的接口(Java的code):
In JavaScript interface(Java code):
void setLocationsData(String param){
//parse JSON here, create Java Object
}
问题是:我webView.loadUrl后得到调用脚本之间的延迟的WebView()和时刻,当数据被返回到我的Java code。 Java的code不等待JS去完成它的业务。我该如何解决这个问题?
The problem is: I've got a delay between calling script in WebView after webView.loadUrl() and moment when data is returned to my Java code. Java code doesn't wait for JS to finish it's business. How do I solve this?
推荐答案
这是我遇到的唯一(哈克)解决方案是使用<一个href=\"http://stackoverflow.com/questions/5820237/android-webview-loadurl-with-javascript-onpagefinished-lag\">one调用使用loadURL后第二次延迟。你可以使用 addJavaSriptInterface()这样做。
The only (hacky) solution that I've come across is using a one second delay after calling the loadUrl. You may use the addJavaSriptInterface() to do so.
或者,如果JS处理时间太长,你必须使用回调
or if the JS processing takes too long you have to use callbacks
<input type="button" value="Say hello" onClick="callYourCallbackFunctionHere('Hello Android!')" />
<script type="text/javascript">
function callYourCallbackFunctionHere(toast) {
Android.callAndroidCallback(toast);
}
</script>
public class JavaScriptInterface {
Context mContext;
/** Instantiate the interface and set the context */
JavaScriptInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
public void callAndroidCallback(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
这篇关于我如何在Android的WebView中的JavaScript,Java的通信同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!