Using WebView to integrate web content into your app

by Admin  on  24. September 2010 01:13

The web browser is perhaps the most important application on any consumer platform these days. Android has a powerful WebKit-based web browser that can be useful not only to end users, but to developers as well. In order for you to be able to integrate the web browser engine into your apps and use it for various purposes, the platform provides the WebView component.

The WebView is very flexible and generally one of the coolest components you get. With it, you can implement features like:

  • Loading and showing actual web pages, for example application manual or news
  • Showing static HTML content that is embedded into your app
  • Allowing the JavaScript inside the WebView to invoke objects in your application
  • Even implementing the whole app UI using HTML and JavaScript – an exotic but viable solution

In this article, we make a very simple Wikipedia search app that shows you the Wikipedia page for any term you enter. In addition to the search input box and the search button, there is a progress bar that shows loading progress.

The complete source is available for download.

 

Step 1: Adding WebView to the layout

WebView is part of the core Android components. Thus, it is very easy to add to your UI layout (see web_view_demo.xml in the source):

 

  <WebView

    android:id="@+id/web_view"

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:layout_margin="2dip"

    android:layout_weight="1.0" /> 

 

Before we forget, let’s add the INTERNET permission to the AndroidManifest.xml file, since we’re going to load web pages from the Internet:

 

<uses-permission

    android:name="android.permission.INTERNET" />

 

As you might notice, the WebView by itself does not give you any controls except the actual canvas where the web page is rendered. There are noback/forward/reload buttons, but there are corresponding API methods in the WebView class (goBack()goForward()reload()) so you can bind yourcustom UI to implement those actions. (In our simple example there is no way to go forward, back or to reload the page – think of it as of an exercise left for you. J)

Step 2: Controlling the WebView from the code

First, in our activity code (WebViewDemoActivity.java) we get a reference to the WebView component:

   webView = (WebView) findViewById(R.id.web_view); 

We’d like to enable JavaScript (it’s disabled by default for security reasons):

     webView.getSettings().setJavaScriptEnabled(true); // enable JS for better page rendering 

In order to open the initial page, let’s just use the loadUrl() method and load the Wikipedia Android page:       

  webView.loadUrl("http://en.wikipedia.org/wiki/Android_(operating_system)");

As you can notice later, the WebView performs all loading jobs in a background thread so it does not block the UI thread when the page is loading.

We have a progress bar in our layout that we’d like to display only when the page is loading, and we’d like it to represent the progress of current page loading. We can do it easily by introducing a custom WebChromeClient (it can do lots of other cool things – be sure to check its javadoc!):

 

       webView.setWebChromeClient(new WebChromeClient() {

         // this will be called on page loading progress

                  @Override

                  public void onProgressChanged(WebView view, int newProgress) {

                        super.onProgressChanged(view, newProgress);

                        loadingProgressBar.setProgress(newProgress);

                        // hide the progress bar if the loading is complete

                        if (newProgress == 100) {

                              loadingProgressBar.setVisibility(View.INVISIBLE);

                        else {

                              loadingProgressBar.setVisibility(View.VISIBLE);

                        }

                  }

        });

 

While WebChromeClient is responsible for WebView’s UI-related behavior, there is also WebViewClient that is responsible for logical decisions thatWebView makes. We use it to make sure WebView opens the URLs that the user clicks inside itself rather than in a new Browser activity (which is the default behavior):

 

        webView.setWebViewClient(new WebViewClient() {

                  @Override

                  public boolean shouldOverrideUrlLoading(WebView view, String url) {

                        if (url.startsWith("http")) {

                              view.loadUrl(url);

                              return true;

                        else {

                              return super.shouldOverrideUrlLoading(view, url);

                        }

                  }

        })

 

Again, you should really read the javadoc for WebViewClient – it might inspire you to introduce some cool features in addition to what you plan to do.

Step 3: TODOs

Our simple app is doing what we wanted it to do. However, there are few things that need to be fixed or just done before it can hit the Market:

  • The mobile Wikipedia displays a stupid search box on top which kind of makes the app useless. J For now, I solve it by scrolling the WebViewdown by a fixed value. A better solution would be to scroll it to the specific element (the main header) using Javascript.
  • When screen orientation changes, the WebView will reset to the initial page. In order to solve this, we need to save the activity state. This is a separate topic that will be covered in one of the future articles.
  • This app really needs forward, back and reload buttons.

Conclusion

We just made a simple WebView-based app. Hope this will help you get your feet wet with this powerful and flexible component, and you will find many cool uses for it in your apps.

 

Related articles

12 Awesome Android Apps that Will Save Your Money
You would have already saved money if you have an Android instead of a iPhone! But here is another...
Avoiding excessive GC in simple apps
If you started your mobile development on a platform like Java ME, you will probably appreciate the ...
Moving from Java Web development to Android
If you are a Java developer interested in learning more about Android, or if you're determined you...

blog comments powered by Disqus
� 2010 WiseAndroid lightdir.com