: Beginning Android

Entertaining the Client

Entertaining the Client

If you are going to use the WebView as a local user interface (vs. browsing the Web), you will want to be able to get control at key times, particularly when users click on links. You will want to make sure those links are handled properly, either by loading your own content back into the WebView, by submitting an Intent to Android to open the URL in a full browser, or by some other means (see Chapter 25).

Your hook into the WebView activity is via setWebViewClient(), which takes an instance of a WebViewClient implementation as a parameter. The supplied callback object will be notified of a wide range of activities, ranging from when parts of a page have been retrieved (onPageStarted(), etc.) to when you, as the host application, need to handle certain user-or circumstance-initiated events, such as onTooManyRedirects() and onReceivedHttpAuthRequest(), etc.

A common hook will be shouldOverrideUrlLoading(), where your callback is passed a URL (plus the WebView itself) and you return true if you will handle the request or false if you want default handling (e.g., actually fetch the Web page referenced by the URL). In the case of a feed reader application, for example, you will probably not have a full browser with navigation built into your reader, so if the user clicks a URL, you probably want to use an Intent to ask Android to load that page in a full browser. But, if you have inserted a fake URL into the HTML, representing a link to some activity-provided content, you can update the WebView yourself.

For example, lets amend the first browser example to be a browser-based equivalent of our original example: an application that, upon a click, shows the current time.

From WebKit/Browser3, here is the revised Java:

publicclass BrowserDemo3extendsActivity {
WebView browser;
public voidonCreate(Bundle icicle) {
browser = (WebView)findViewById(R.id.webkit);
voidloadTime() {
String page="<html><body><a href="clock">"
+ new Date().toString() + "</a></body></html>";
browser.loadDataWithBaseURL("x-data://base", page,
"text/html", "UTF-8", null);
privateclass Callbackextends WebViewClient {
public booleanshouldOverrideUrlLoading(WebView view, String url) {

Here, we load a simple Web page into the browser (loadTime()) that consists of the current time, made into a hyperlink to the /clock URL. We also attach an instance of a WebViewClient subclass, providing our implementation of shouldOverrideUrlLoading(). In this case, no matter what the URL, we want to just reload the WebView via loadTime().

Running this activity gives the result shown in Figure 13-3.

Figure 13-3.The Browser3 sample application

Selecting the link and clicking the D-pad center button will click the link, causing us to rebuild the page with the new time.

: 1.047. /Cache: 3 / 1