Returning value from Javascript *reliably* to Webview

北慕城南 提交于 2021-02-19 08:38:17

问题


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?

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?

My current code looks like this:

In 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");

In javascript:

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

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?


回答1:


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


来源:https://stackoverflow.com/questions/6205627/returning-value-from-javascript-reliably-to-webview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!