从JavaScript可靠地返回值到Webview [英] Returning value from Javascript *reliably* to Webview

查看:78
本文介绍了从JavaScript可靠地返回值到Webview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一种方法可以从webview调用javascript函数,然后让其调用Java中的方法以返回结果.如中所述的方法,如何从javascript获取返回值在android的webview中?

There is a way to call javascript function from webview and then let it call a method in Java to return the result. Like described in How to get return value from javascript in webview of android?

现在,javascript函数可能会失败(例如由于javascript文件中的错字).在这种情况下,我想用Java执行一些故障转移代码.有什么好方法吗?

Now, the javascript function can fail (say due to a typo in javascript file). In that case, I would like to carry out some failover code in Java. What is a good way to do that?

我当前的代码如下:

在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中

In javascript:

function handleEvent() {
    var success =  doSomething();
    if (success) {
        eventManager.setEventHandled();
    }   
}

这对于我的情况似乎很好.是否有比休眠一段时间并希望Java调用到此结束"方法更好的方法?

This seems to work fine for my case. Is there a better way than this "sleep for sometime and hope Javascript call is finished by then" method?

推荐答案

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

You can use a synchronization object for notifying and waiting:

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可靠地返回值到Webview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆