Android Tutorial

(avery) #1

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:


  1. Create a new Android application.

  2. 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.

  3. In the onCreate() method of your application activity, retrieve the WebView
    control using the findViewById() method.

  4. Enable JavaScript within the WebView by retrieving its WebSettings and
    calling the setJavaScriptEnabled() method.

  5. Create a WebChromeClient object and implement its onConsoleMessage()
    method in order to monitor the JavaScript console messages.

  6. Add the WebChromeClient object to the WebView using the
    setWebChromeClient() method.

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

Free download pdf