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

1
<uses-permission android:name="android.permission.INTERNET" />

How to load a Web page using an URL

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

How to load data from an HTML String

1
2
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.0" encoding="utf-8"?>
    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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
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
 
    }
 
 //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);
 }
 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s