【问题标题】:Returning value from Javascript *reliably* to Webview从 Javascript *reliably* 返回值到 Webview
【发布时间】:2011-09-06 12:45:06
【问题描述】:

有一种方法可以从 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 调用到那时完成”方法更好的方法?

【问题讨论】:

    标签: android webview android-webview


    【解决方案1】:

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

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

    【讨论】:

    • 如果 javascript 函数失败并且 setEventHandled() 没有被调用,我想运行一些故障转移代码(如问题所示)。这个答案只会阻止等待javascript调用成功,不是吗?
    • 使用block方法超时。
    猜你喜欢
    • 2017-06-06
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    相关资源
    最近更新 更多