Webview Javascript calling method java - android

0

I have a webview app that calls an index.html:

WebView webView = (WebView)findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebViewClient(new webViewClient());
    webView.loadUrl("file:///android_asset/index.html");
    webView.addJavascriptInterface(this, "android");

In this index I have a javascript that accesses a java function to check if there is a connection, if the return is true it sends to my site:

function connection(){
   return android.CheckConnection();
}
if(!connection()){
   alert('sem conexão');
}else{
   window.location.href = 'http://meusite.com';
}

java function accessed by javascript

@JavascriptInterface
public boolean CheckConnection(){
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}

When my site loads, it attempts to access the java functions just as I did with the index.html but a "Uncaught Error: Java exception was raised during method invocation" error is returned

    
asked by anonymous 21.06.2016 / 07:21

1 answer

0

Gustavo speaks,

Try changing this line:

webView.addJavascriptInterface(this, "android");

For this:

webView.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");

And outside of your onCreate, put this method:

/* An instance of this class will be registered as a JavaScript interface */
    class MyJavaScriptInterface
    {
        @JavascriptInterface
        @SuppressWarnings("unused")
        public void processHTML(String html)
        {
            // process the html as needed by the app
        }
    }

Hugs.

    
21.06.2016 / 15:08