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.

Prerequisite

You must have the knowledge of binding Android and Javascript code before you proceed with developing application. If you are new to Android and Javascript code binding, take a look at How to bind Javascript code to Android code?.


Video Demo

Quick Links

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.prgguru.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, discuss it right away in the comment section.

package com.prgguru.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("http://apps.programmerguru.com/examples/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.

androidjsbinding_thirdbtn

package com.prgguru.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("http://apps.programmerguru.com/examples/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 – http://apps.programmerguru.com/examples/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>

[pglinkadssmall1]

Demo

That’s all. It’s time to test our code.

Run the application using emulator or device by right clicking on the project >> Run as >> Android applicaiton >> Choose emulator or device.



Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse). If you just want to run the application in your mobile and see the output but don’t want to hit your head with source code, download application(apk) file and install it in your mobile device.

Download Source Code Download Application(apk)

*apk in Android  is the installation file similar to exe in windows.

[pglinkadssmall]

If you feel this article is helpful and interesting please spread a word about it to your friends and colleagues by sharing the article in Facebook or Twitter.

You are always welcome to provide your comments and feedback from comment box.

Reference
Android Javascript Binding
[pgwriteforus]
[pgfeedback]

Author: Android Guru

Share This Post On
  • mohini

    how to load dynamic page ?

    I want to say , in this example “http://apps.programmerguru.com/examples/chennai.html” loading this page, set this link hard coded.

    If I want to load dynamically pages in this case what to do?
    please help me.

  • tormahiri

    thanks sir very amazing

Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest

Shares