How to set up Java-to-Java sync in Android WebView?

I have a WebView, JS code inside it. Also I have an interface to call a Java method from a WebView into Java code. I need to transfer data from JS to Java. ... To do this:

webView.loadUrl("javascript:getData()");

//Obtain Java object here

      

In JavaScript:

function gataData () {
    //serialize data to JSON, pass it as 'native' function param
    JSInterface.setLocationsData(data);// This calls a Java function setLocationsData(String param)
}

      

In JavaScript frontend (Java code):

 void setLocationsData(String param){
    //parse JSON here, create Java Object
 }

      

The problem is that I have a delay between the script call in the WebView after webView.loadUrl () and the moment the data is returned to the Java code. Java code didn't wait for JS business to finish. How to solve this?

0


source to share


1 answer


The only (hacky) solution I have come across is using one second delay after calling loadUrl. You can use addJavaSriptInterface () for this.

or if JS processing takes too long you need to use callbacks

<input type="button" value="Say hello" onClick="callYourCallbackFunctionHere('Hello Android!')" />

<script type="text/javascript">
    function callYourCallbackFunctionHere(toast) {
        Android.callAndroidCallback(toast);
    }
</script>

      




public class JavaScriptInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    JavaScriptInterface(Context c) {
        mContext = c;
    }

    /** Show a toast from the web page */
    public void callAndroidCallback(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
}

      

+2


source







All Articles