我在里面有WebView,JS代码。此外,我还有接口,允许从WebView调用Java方法到Java代码。--我需要将数据从JS传递到Java.:
webView.loadUrl("javascript:getData()");
//Obtain Java object here在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代码)中:
void setLocationsData(String param){
//parse JSON here, create Java Object
}问题是:在WebView中调用webView.loadUrl()后的脚本与数据返回到Java代码之间存在延迟。Java代码不会等待JS完成它的业务。我该怎么解决这个问题?
发布于 2011-10-24 01:48:13
我遇到的唯一(hacky)解决方案是在调用一秒延迟之后使用loadUrl。您可以使用addJavaSriptInterface()来做到这一点。
或者,如果JS处理时间过长,则必须使用回调。
<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();
}
}https://stackoverflow.com/questions/7869372
复制相似问题