Android WebView Example

Android WebView is an extension of the View class that helps display web content. You can have the web view take the complete layout or just a portion of the screen. Say for example you want to print an Address and then display it using Google Maps inside a WebView. It doesn't support all features of a regular browser but you can enable Javascript inside your Web View and also override the Back button to view if there are any history pages. With the help of the JavaScriptInterface you can use JavaScript to call functions inside the Activity. That way you can use the Alert Builder to display alerts instead of plain Javascript alert function and much more. Also you can choose to open links in the same WebView or not, by default all links will open in the default browser window.

Please note: In order for your Activity to access the Internet and load web pages in a WebView, you must add the INTERNET permissions to your Android Manifest file
<uses-permission android:name="android.permission.INTERNET" />

How to load a Web page using an URL

webview.loadUrl("http://www.google.com/");

How to load data from an HTML String

String myHtml = "<html><body>A very basic <b>WebView</b> demo!</body></html>";
webview.loadData(myHtml, "text/html", null);
Android WebView Example
Android WebView Alert Example

Android Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.as400samplecode"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />
 <uses-permission android:name="android.permission.INTERNET" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" 
        android:theme="@android:style/Theme.Holo.Light">>
        <activity
            android:name=".AndroidWebViewActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Android Layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="10dp"
        android:text="@string/hello"
        android:textSize="20sp" />

    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Android Activity

package com.as400samplecode;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class AndroidWebViewActivity extends Activity {
    
 private WebView myWebView;
 private String LOG_TAG = "AndroidWebViewActivity";
 
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        myWebView = (WebView) findViewById(R.id.webView1);
        
        //enable Javascript
        myWebView.getSettings().setJavaScriptEnabled(true);
        
        //loads the WebView completely zoomed out
        myWebView.getSettings().setLoadWithOverviewMode(true);
        
        //true makes the Webview have a normal viewport such as a normal desktop browser 
        //when false the webview will have a viewport constrained to it's own dimensions
        myWebView.getSettings().setUseWideViewPort(true);
        
        //override the web client to open all links in the same webview
        myWebView.setWebViewClient(new MyWebViewClient());
        myWebView.setWebChromeClient(new MyWebChromeClient());
        
        //Injects the supplied Java object into this WebView. The object is injected into the 
        //JavaScript context of the main frame, using the supplied name. This allows the 
        //Java object's public methods to be accessed from JavaScript.
        myWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
        
        //load the home page URL
        myWebView.loadUrl("http://demo.mysamplecode.com/Servlets_JSP/pages/androidWebView.jsp");
 
    }
 
 //customize your web view client to open links from your own site in the 
 //same web view otherwise just open the default browser activity with the URL
 private class MyWebViewClient extends WebViewClient {
     @Override
     public boolean shouldOverrideUrlLoading(WebView view, String url) {
         if (Uri.parse(url).getHost().equals("demo.mysamplecode.com")) {
             return false;
         }
         Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
         startActivity(intent);
         return true;
     }
 }
 
 private class MyWebChromeClient extends WebChromeClient {
     
  //display alert message in Web View
  @Override
     public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
         Log.d(LOG_TAG, message);
         new AlertDialog.Builder(view.getContext())
          .setMessage(message).setCancelable(true).show();
         result.confirm();
         return true;
     }

 }
 
 public class JavaScriptInterface {
     Context mContext;

     // Instantiate the interface and set the context 
     JavaScriptInterface(Context c) {
         mContext = c;
     }
     
     //using Javascript to call the finish activity
     public void closeMyActivity() {
         finish();
     }
     
 }
 
 //Web view has record of all pages visited so you can go back and forth
 //just override the back button to go back in history if there is page
 //available for display
 @Override
 public boolean onKeyDown(int keyCode, KeyEvent event) {
     if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
         myWebView.goBack();
         return true;
     }
     return super.onKeyDown(keyCode, event);
 }
 
}

Recommended Reading

References