Webview Javascript calling java method - android

Asked

Viewed 875 times

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 is loaded, it tries to access the java functions just like I did with index.html but an error is returned "Uncaught Error: Java Exception was Raised During method Invocation"

1 answer

0


Fala Gustavo,

Try to change that line:

webView.addJavascriptInterface(this, "android");

For that reason:

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

And out of your mind, 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.

  • Leonardo, should my Checkconnection function be within the Myjavascriptinterface class? I did this way and the error persists, but the problem got worse because now the site jquery also stopped working

  • What error do you see in your Logcat? Same as before?

  • I found that running the app usually everything is working, but this error happens when the app is closed (clear data) and it receives a notification, by clicking on the notification it starts the app that after loading the webview with jquery, jquery runs a java method and at that moment the error happens, remembering that the error happens only when I start the app via notification...logcat is the same yes Leonardo

Browser other questions tagged

You are not signed in. Login or sign up in order to post.