Javascript Interface for Android and Javascript communication

The following is an example of two way communication between Android code and Javascript in a WebView.

Enable internet permission and register the WebViewActivity class

<uses-permission android:name="android.permission.INTERNET"/>

<activity android:name=".WebViewActivity"/>

The layout for the WebViewActivity class

<?xml version="1.0" encoding="utf-8"?>
<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

The WebAppInterface.java for communcating between Android and javascript.

import android.content.Context;
import android.os.Build;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

public class WebAppInterface {
    Context mContext;

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

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

    @JavascriptInterface
    public int getAndroidVersion() {
        return android.os.Build.VERSION.SDK_INT;
    }

    @JavascriptInterface
    public void showAndroidVersion(String versionName) {
        Toast.makeText(mContext, versionName, Toast.LENGTH_SHORT).show();
    }

}

The WebView class WebViewActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebViewActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);

        WebView webView = (WebView) findViewById(R.id.webview);
        webView.loadUrl("file:///android_asset/index.html");

        webView.addJavascriptInterface(new WebAppInterface(this), "AndroidInterface"); // To call methods in Android from using js in the html, AndroidInterface.showToast, AndroidInterface.getAndroidVersion etc
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.setWebViewClient(new MyWebViewClient());
        webView.setWebChromeClient(new MyWebChromeClient());
    }


    private class MyWebViewClient extends WebViewClient {
        @Override
        public void onPageFinished (WebView view, String url) {
            //Calling a javascript function in html page
            view.loadUrl("javascript:alert(showVersion('called by Android'))");
        }
    }

    private class MyWebChromeClient extends WebChromeClient {
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            Log.d("LogTag", message);
            result.confirm();
            return true;
        }
    }
}

The html file in assets folder, index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <title>Hello</title>

    <style>
      body, html {
        height: 100%;
        text-align: center;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #F89821;
        background-color: #ffffff;
        padding: 20px;
        margin-bottom: 100px;
      }
    </style>

  </head>
  <body>
      <input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
      <br/><br/>
      <input type="button" value="Show Version" onClick="showVersion('called within the html')" />
      <br/><br/>
      <p id="version"></p>
      <script type="text/javascript">
        <!-- Sending value to Android -->
        function showAndroidToast(toast) {
            AndroidInterface.showToast(toast);
        }

        <!-- Getting value from Android -->
        function showVersion(msg) {
            var myVar = AndroidInterface.getAndroidVersion();
            document.getElementById("version").innerHTML = msg + " You are running API Version " + myVar;
        }
      </script>
  </body>
</html>

Complete example in Github

Search within Codexpedia

Custom Search

Search the entire web

Custom Search