Embedding browser view in Android application


         Android provides a wrapper around the WebKit browser engine called WebView. This can be used to get the real power of the browser in our application. WebView works almost similar to any other Android views except that it has some extra methods specific to the browser.
In Android all it takes is three lines of code.To demonstrate this, lets create an application called "BrowserView". This will have two layout files, first one will have the text field to get the URL from the user and a GO button. The second layout will be used to show the webpage.

Layout files:
activity_main.xml:

<?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" >
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        <EditText
            android:id="@+id/url_field"
            android:layout_width="142dp"
            android:layout_height="wrap_content"
            android:layout_weight="1.0"
            android:imeOptions="actionGo"
            android:inputType="textUri"
            android:lines="1" />
        <Button
            android:id="@+id/go_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Go" />
    </LinearLayout>
</LinearLayout>

On EditText we set android:layout_weight="1.0" to make the text area fill up all the horizontal space to the left of the GO button. And also android:lines="1"  limits the height of text area to one vertical line. But this has no effect on the amount of text the user enters. This is just to control the way it is displayed.

browser_view.xml

<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/web_view"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1.0" />

This layout xml file has the WebView element on which the website will be displayed.

Activity classes:
We have two activity classes in this example. The first activity will render activity_main.xml layout and get the url from the user. On clicking the 'GO' button, it will generate an Intent to invoke the second activity.
The url value will passed to the second activity using setExtra() method of the intent.

MainActivity.java:

package com.example.browserview;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class MainActivity extends Activity {
 private EditText urlText;
 private Button goButton;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  urlText = (EditText) findViewById(R.id.url_field);
  goButton = (Button) findViewById(R.id.go_button);
  // Setup event handlers
  goButton.setOnClickListener(new OnClickListener() {
    public void onClick(View view) {
      Intent launchactivity= new Intent(MainActivity.this,BrowserActivity.class);     
      launchactivity.putExtra("url", urlText.getText());
      startActivity(launchactivity);          
      }
  });
  urlText.setOnEditorActionListener(new OnEditorActionListener()                 {
  public boolean onEditorAction(TextView v, int actionId,
    KeyEvent event) {
    if (actionId == EditorInfo.IME_NULL) {
      Intent launchactivity= new Intent(MainActivity.this,BrowserActivity.class); 
      launchactivity.putExtra("url", urlText.getText());
      startActivity(launchactivity); 
      InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
      imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
      return true;
    }
    return false;
        }
      });
 }
 
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
   // Inflate the menu; this adds items to the action bar if it is present. 
        getMenuInflater().inflate(R.menu.activity_main, menu);
 return true;
 }

}


New Intent is created to invoke the second activity as shown below;

Intent launchactivity= new Intent(MainActivity.this,BrowserActivity.class);     
launchactivity.putExtra("url", urlText.getText());
startActivity(launchactivity);

Here, MainActivity.this is the current context and BrowserActivity.class is the second activity class to be invoked.
putExtra("Key","value") is used to send the url value to the second activity.
startActivity() will invoke the activity.

As a convenience, if the user types an address and hits Enter key, we want to the website to load just like they click 'GO' button. To do this we have defined a listener that will be called every time the user types a keystroke into the edit field. If it is 'Enter keystroke' then the second activity will be invoked.


BrowserActivity.java:

package com.example.browserview;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class BrowserActivity extends Activity {
 private WebView webView;

 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.browser_view);
  String url = getIntent().getExtras().get("url").toString();
  webView = (WebView) findViewById(R.id.web_view);
  openBrowser(url);
 }

 /** Open a browser on the URL specified in the text box */
 private void openBrowser(String url) {
  webView.getSettings().setJavaScriptEnabled(true);
  if(!url.trim().startsWith("http://")){
   url="http://"+url.trim();
  }
  webView.loadUrl(url.trim());
 }
}

First this we have to do in this activity class is, getting the url value from the Intent.
getIntent().getExtras().get("url").toString();
Above statement will give us the value assigned for the key "url". getIntent().getExtras() will give us the Boundle. get("key") method can be used to fetch the values.

Note: Don't forget to include http:// . If we miss this, Android won't understand how to handle this address.

AndroidManifest.xml:
Don't forget to add INTERNET permission in your manifest.
<uses-permission android:name="android.permission.INTERNET"/>
Entire manifest file is given below;

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
         <activity
            android:name=".BrowserActivity"
            android:theme="@android:style/Theme.NoTitleBar" />
        <activity
            android:name="com.example.browserview.MainActivity"
            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>

Output screenshots:





Source Code of this application:
BrowserView.zip






Reactions:

1 comment :

  1. Thank you this tutorial is very helpful for me...thanks again

    ReplyDelete