By : Ketan Bhimani
386
maintain. However, on its own, a web application cannot call into
native platform code and take advantage of the features that native
apps (such as those written in Java for the Android platform) can,
such as using a built-in camera or accessing some other underlying
Android feature.
Developers can enhance web applications by designing a
lightweight shell application in Java and using a WebView control as
a portal to the web application content. Two-way communication
between the web application and the native Java application is
possible through scripting languages such as JavaScript.
Let’s create a simple Android application that illustrates
communication between web content and native Android code. This
example requires that you understand JavaScript. To create this
application, take the following steps:
- Create a new Android application.
- Create a layout with a WebView control called html_viewer and a Button
control called call_js. Set the onClick attribute of the Button control to a
method called setHTMLText. - In the onCreate() method of your application activity, retrieve the WebView
control using the findViewById() method. - Enable JavaScript within the WebView by retrieving its WebSettings and
calling the setJavaScriptEnabled() method. - Create a WebChromeClient object and implement its onConsoleMessage()
method in order to monitor the JavaScript console messages. - Add the WebChromeClient object to the WebView using the
setWebChromeClient() method. - Allow the JavaScript interface to control your application by calling the
addJavascriptInterface() method of the WebView control. You will need to
define the functionality that you want the JavaScript interface to be able to
control and within what namespace the calls will be available. In this case,
we allow the JavaScript to initiate Toast messages.