Friday , March 22 2019
Home / Android / Binding JavaScript and Android Code – Example

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:
Open 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.

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.


AndroidManifest.xml permission

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


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.

HTML – androidjs.html
Create a html page with below code. You can refer source of this URL as well – to know how Javascript functions are written.


About admin

Check Also

Android Activity Launch Modes

Launch mode is an instruction for Android OS which specifies how the activity should be ...

Leave a Reply