19 9月 2008
I've written a small application called WebViewDemo that shows how you can add web content to your application. You can find it in the apps-for-android project. This application demonstrates how you can embed a WebView into an activity and also how you can have two way communication between your application and the web content.
A WebView uses the same rendering and JavaScript engine as the browser, but it runs under the control of your application. The WebView can be full screen or you can mix it with other Views. The content for your WebView can come from anywhere. The WebView can download content from the web, or it can come from local files stored in your assets directory. The content can even be dynamically generated by your application code. For this example, the HTML comes from a local file called demo.html.
This application does not do very much: when you click on the android, he raises his arm.
This could, of course, easily be accomplished with a little bit of JavaScript. Instead, though, WebViewDemo takes a slightly more complicated path to illustrate two very powerful features of WebView.
First, JavaScript running inside the WebView can call out to code in your Activity. You can use this to have your JavaScript trigger actions like starting a new activity, or it can be used to fetch data from a database or ContentProvider. The API for this is very simple: just call the addJavascriptInterface method on your WebView. You pass an object whose methods you want to expose to JavaScript and the name to use when making calls. You can see the exact syntax in WebViewDemo.java. Here we are making our DemoJavascriptInterface object available to JavaScript where it will be called "window.demo".
Second, your Activity can invoke JavaScript methods. All you have to do is call the loadUrl method with the appropriate JavaScript call:
mWebView.loadUrl("javascript:wave()");
Our WebViewDemo uses both techniques: when you click on the android, it calls out to the activity, which then turns around and calls back into the JavaScript. WebViews are very powerful, and they may be a valuable tool to help you build your application – especially if you already have a lot of HTML content. As it happens, we've used exactly this approach in some of the applications we've written.