Thursday , November 21 2024

Binding JavaScript and Android Code – Example

When developing a web application that’s designed specifically for the WebView in your Android application, you can create interfaces between your JavaScript code and client-side Android code. For example, your JavaScript code can call a method in your Android code to display a Dialog, instead of using JavaScript’s alert() function.

In this post we are going to develop simple Android application to demonstrate how to bridge Javascript and Android code.

Project Structure

  • Create new android project [File >> New >> Android Application Project] with project name AndroidJSWebView
  • Choose Build SDK and minimum required SDK [I chose version 4.1 and 2.2]
  • Enter package name as ‘com.w2class.example’
  • Click next and select BlankActivity
  • Click next and provide Activity name and Layout name as ‘AndroidJSWebView’ and ‘main’ respectively.

Code Listings

Open main.xml, now you can view the layout as either XML or in graphical view and just replace the XML with below one:

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
    <WebView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/webkit"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</ScrollView>

AndroidJSWebView.java
Open AndroidJSWebView.java and replace it with below code. Each line is added with comment and I hope it is self understandable. If you still have any doubt/question, comments it right away in the comment section.

package com.w2class.example;
 
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
 
public class AndroidJSWebView extends Activity {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //WebView Object
        WebView browser;
        browser=(WebView)findViewById(R.id.webkit);
        //Enable Javascript
        browser.getSettings().setJavaScriptEnabled(true);
        //Inject WebAppInterface methods into Web page by having Interface name 'Android'
        browser.addJavascriptInterface(new WebAppInterface(this), "Android");
        //Load URL inside WebView
        browser.loadUrl("https://w2class.com/android-tutorial/androidjs.html");
    }
    //Class to be injected in Web page
    public class WebAppInterface {
        Context mContext;
 
        /** Instantiate the interface and set the context */
        WebAppInterface(Context c) {
            mContext = c;
        }
 
        /**
         * Show Toast Message
         * @param toast
         */
        public void showToast(String toast) {
            Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
        }
 
        /**
         * Show Dialog
         * @param dialogMsg
         */
        public void showDialog(String dialogMsg){
            AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();
 
            // Setting Dialog Title
            alertDialog.setTitle("JS triggered Dialog");
 
            // Setting Dialog Message
            alertDialog.setMessage(dialogMsg);
 
            // Setting alert dialog icon
            //alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
 
            // Setting OK Button
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Toast.makeText(mContext, "Dialog dismissed!", Toast.LENGTH_SHORT).show();
                }
            });
 
            // Showing Alert Message
            alertDialog.show();
        }
 
        /**
         * Intent - Move to next screen
         */
        public void moveToNextScreen(){
             AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
             // Setting Dialog Title
             alertDialog.setTitle("Alert");
             // Setting Dialog Message
             alertDialog.setMessage("Are you sure you want to leave to next screen?");
             // Setting Positive "Yes" Button
             alertDialog.setPositiveButton("YES",
                     new DialogInterface.OnClickListener() {
                         public void onClick(DialogInterface dialog, int which) {
                             //Move to Next screen
                             Intent chnIntent = new Intent(AndroidJSWebView.this, ChennaiIntent.class); 
                             startActivity(chnIntent); 
                         }
                     });
             // Setting Negative "NO" Button
             alertDialog.setNegativeButton("NO",
                     new DialogInterface.OnClickListener() {
                         public void onClick(DialogInterface dialog, int which) {
                             // Cancel Dialog
                             dialog.cancel();
                         }
                     });
             // Showing Alert Message
             alertDialog.show();
        }
    }
}

 

ChennaiIntent.java

Create an Activity called ChennaiIntent and make sure you included it in AndroidManifest.xml. It is a second screen which will be shown to user when third button from the UI is clicked.

package com.w2class.example;
 
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
 
public class ChennaiIntent extends Activity {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        WebView browser;
        browser=(WebView)findViewById(R.id.webkit);  
        browser.getSettings().setJavaScriptEnabled(true);
        browser.loadUrl("https://w2class.com/android-tutorial/chennai.html");
    }
}

 

AndroidManifest.xml permission

Don’t forget to add internet permissions in AndroidManifest.xml:

<!-- Permission: Allow application to connect to Internet -->
<uses-permission android:name="android.permission.INTERNET" />

 

Javascript Code

Here is the Javascript code which invokes Android methods using the interface name ‘Android’. The interface  ‘Android’ was created using method ‘addJavascriptInterface()’ by injecting the Class WebAppInterface.

<script type="text/javascript">
    function showAndroidToast(toastmsg) {
        Android.showToast(toastmsg);
    }
 function showAndroidDialog(dialogmsg) {
        Android.showDialog(dialogmsg);
    }
 function moveToScreenTwo() {
        Android.moveIntent();
    }
</script>

HTML – androidjs.html
Create a html page with below code. You can refer source of this URL as well – https://w2class.com/android-tutorial/androidjs.html to know how Javascript functions are written.

<html>
<head>
<style>
body{
background-color: #FA5858;
color:#fff;
}
input{
background-color: #F7D358;
width: 300px;
padding:10px;
color: #000;
}
div#content{
padding:20px;
background-color: #F7D358;
color: #000;
}
</style>
<script type="text/javascript">
    function showAndroidToast(toastmsg) {
        Android.showToast(toastmsg);
    }
 function showAndroidDialog(dialogmsg) {
        Android.showDialog(dialogmsg);
    }
 function moveToScreenTwo() {
        Android.moveToNextScreen();
    }
</script>
</head>
<body>
<center>
<h3>Binding JavaScript code to Android code</h3>
<div id="content">
When developing a web application that's designed specifically for the WebView in your Android application, you can create interfaces between your JavaScript code and client-side Android code. For example, your JavaScript code can call a method in your Android code to display a Dialog, instead of using JavaScript's alert() function.
</div>
<div>
Here are few examples:
</div>
<div>
<input type="button" value="Make Toast" onClick="showAndroidToast('Toast made by Javascript :)')" /><br/>
<input type="button" value="Trigger Dialog" onClick="showAndroidDialog('This dialog is triggered by Javascript :)')" /><br/>
<input type="button" value="Take me to Next Screen" onClick="moveToScreenTwo()" />
</div>
</center>
</body>
</html>

 

About admin

Check Also

Custom Font in android

In this post, we’ll look at a generalized approach, which is more complex, but also …

Leave a Reply