有一种方法可以从 webview 调用 javascript 函数,然后让它调用 Java 中的方法返回结果。如 How to get return value from javascript in webview of android? 中所述
现在,javascript 函数可能会失败(比如由于 javascript 文件中的拼写错误)。在这种情况下,我想用 Java 执行一些故障转移代码。这样做的好方法是什么?
我当前的代码如下所示:
在 Java 中:
private boolean eventHandled = false;
@Override
public void onEvent() {
eventHandled = false;
webview.loadUrl("javascript:handleEvent()");
// Wait for JS to handle the event.
try {
Thread.sleep(500); // milliseconds
} catch (InterruptedException e) {
// log
}
if (!eventHandled) {
// run failover code here.
}
}
public final MyActivity activity = this;
public class EventManager {
// This annotation is required in Jelly Bean and later:
@JavascriptInterface
public void setEventHandled() {
eventHandled = true;
}
};
webview.addJavascriptInterface(new EventManager(), "eventManager");
在 JavaScript 中:
function handleEvent() {
var success = doSomething();
if (success) {
eventManager.setEventHandled();
}
}
这似乎很适合我的情况。有没有比这种“休眠一段时间并希望 Javascript 调用到那时完成”方法更好的方法?
最佳答案
您可以使用同步对象来通知和等待:
public class EventManager {
private final ConditionVariable eventHandled = new ConditionVariable();
public void setEventHandled() {
eventHandled.open();
}
void waitForEvent() {
eventHandled.block();
}
}
private final EventManager eventManager = new EventManager();
@Override
public void onEvent() {
webview.loadUrl("javascript:handleEvent()");
// Wait for JS to handle the event.
eventManager.waitForEvent();
}
关于android - 将值从 Javascript *可靠地* 返回到 Webview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6205627/