从Javascript *可靠*返回值到Webview

时间:2011-06-01 17:59:34

标签: android webview android-webview

有一种方法可以从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调用完成然后”方法?

1 个答案:

答案 0 :(得分:5)

您可以使用同步对象通知和等待:

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