Выбрать главу

• clearCache() to clear the browser resource cache and clearHistory() to clear the browsing history

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, let’s 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:

public class BrowserDemo3 extends Activity {

 WebView browser;

 @Override

 public void onCreate(Bundle icicle) {

  super.onCreate(icicle);

  setContentView(R.layout.main);

  browser = (WebView)findViewById(R.id.webkit);

  browser.setWebViewClient(new Callback());

 loadTime();

}

 void loadTime() {

  String page="<html><body><a href=\"clock\">"

   + new Date().toString() + "</a></body></html>";

  browser.loadDataWithBaseURL("x-data://base", page,

   "text/html", "UTF-8", null);

 }

  private class Callback extends WebViewClient {

   public boolean shouldOverrideUrlLoading(WebView view, String url) {

    loadTime();

   return(true);

  }

 }

}

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.

Settings, Preferences, and Options (Oh, My!)

With your favorite desktop Web browser, you have some sort of “settings” or “preferences” or “options” window. Between that and the toolbar controls, you can tweak and twiddle the behavior of your browser, from preferred fonts to the behavior of Javascript.

Similarly, you can adjust the settings of your WebView widget as you see fit, via the WebSettings instance returned from calling the widget’s getSettings() method.

There are lots of options on WebSettings to play with. Most appear fairly esoteric (e.g., setFantasyFontFamily()). However, here are some that you may find more usefuclass="underline"

• Control the font sizing via setDefaultFontSize() (to use a point size) or setTextSize() (to use constants indicating relative sizes like LARGER and SMALLEST)

• Control Javascript via setJavaScriptEnabled() (to disable it outright) and setJavaScriptCanOpenWindowsAutomatically() (to merely stop it from opening pop-up windows)

• Control Web site rendering via setUserAgent() — 0 means the WebView gives the Web site a user-agent string that indicates it is a mobile browser, while 1 results in a user-agent string that suggests it is a desktop browser

The settings you change are not persistent, so you should store them somewhere (such as via the Android preferences engine) if you are allowing your users to determine the settings, versus hard-wiring the settings in your application.

CHAPTER 14

Showing Pop-Up Messages

Sometimes your activity (or other piece of Android code) will need to speak up.

Not every interaction with Android users will be neat, tidy, and containable in activities composed of views. Errors will crop up. Background tasks may take way longer than expected. Something asynchronous may occur, such as an incoming message. In these and other cases, you may need to communicate with the user outside the bounds of the traditional user interface.

Of course, this is nothing new. Error messages in the form of dialog boxes have been around for a very long time. More-subtle indicators also exist, from task-tray icons to bouncing dock icons to a vibrating cell phone.

Android has quite a few systems for letting you alert your users outside the bounds of an Activity-based UI. One, notifications, is tied heavily into intents and services and, as such, is covered in Chapter 32. In this chapter, you will see two means of raising pop-up messages: toasts and alerts.

Raising Toasts

A Toast is a transient message, meaning that it displays and disappears on its own without user interaction. Moreover, it does not take focus away from the currently active Activity, so if the user is busy writing the next Great American Programming Guide, they will not have keystrokes be “eaten” by the message.

Since a Toast is transient, you have no way of knowing if the user even notices it. You get no acknowledgment from them, nor does the message stick around for a long time to pester the user. Hence, the Toast is mostly for advisory messages, such as indicating a long-running background task is completed, the battery has dropped to a low-but-not-too-low level, etc.

Making a Toast is fairly easy. The Toast class offers a static makeText() that accepts a String (or string resource ID) and returns a Toast instance. The makeText() method also needs the Activity (or other Context) plus a duration. The duration is expressed in the form of the LENGTH_SHORT or LENGTH_LONG constants to indicate, on a relative basis, how long the message should remain visible.

If you would prefer your Toast be made out of some other View, rather than be a boring old piece of text, simply create a new Toast instance via the constructor (which takes a Context), then call setView() to supply it with the view to use and setDuration() to set the duration.

Once your Toast is configured, call its show() method, and the message will be displayed.