Android Tutorial

(avery) #1
Android Tutorial 389






The sample.html file defines four JavaScript functions and displays
the form shown within the WebView:

 The doToast() function calls into the Android application using the jse
object defined earlier with the call to the addJavaScriptInterface() method.
The add JavaScriptInterface() method, for all practical intents and
purposes, can be treated literally as the JavaScriptExtensions class as if
that class had been written in JavaScript. If the doToast() function had
returned a value, we could assign it to a variable here.
 The doConsoleLog() function writes into the JavaScript console log, which
is picked up by the onConsoleMessage() callback of the
WebChromeClient.
 The doAlert() function illustrates how alerts work within the WebView
control by launching a dialog. If you want to override what the alert looks
like, you can override the WebChromeClient.onJSAlert() method.
 The doSetFormText() function illustrates how native Java code can
communicate back through the JavaScript interface and provide data to
the web application.

Finally, to demonstrate making a call from Java back to JavaScript,
you need to define the click handler for the Button control within
your Activity class. Here, the onClick handler, called setHTMLText(),
executes some JavaScript on the currently loaded page by calling a
JavaScript function called doSetFormText(), which we defined
earlier in the web page. Here is an implementation of the
setHTMLText() method:

public void setHTMLText(View view) {
WebView wv = (WebView) findViewById(R.id.html_viewer);
wv.loadUrl(“javascript:doSetFormText(„Java->JS call‟);”);
}

Free download pdf