Create an easy WebView Android Application

Creating an Android WebView application is fairly simple and easy, whether you want load a remote URL or display pages stored in your app. This tutorial walks you through creating a new Android Project, adding a WebView, loading a remote URL, and then loading a local HTML page.

Note: This tutorial helps you create the app from scratch so it assumes you’re a beginner with limited or no experience with the Android development environment, but have some experience with Java.

Getting started:

If you want to deliver a web application (or just a web page) as a part of a client application, you can do it using WebView. The WebView class is an extension of Android’s View class that allows you to display web pages as a part of your activity layout. It does not include any features of a fully developed web browser, such as navigation controls or an address bar. All that WebView does, by default, is show a web page. So lets head up and start our WebView Application.

Creating a new project:

We assume you already have the Android Studio installed on your Computer, so we’ll start by creating a new project by following the steps below : 

1.Create a new project:

This should open up a pop up window in which you’ll be asked to fill the needed information about your Application such as  Application Name,  Domain and Project location like the following picture shows:

2.  Select the Proper Target SDK:

Note: If you only intend to support the Chromium WebView (rather than the old WebKit WebView) set Minimum required SDK to API19: Android4.4 (KitKat).

3. Select Main Activity:

The next page lets you select the main Android activity for your application. For the purposes of this guide, select Empty Activity and click Next.

Note: After you have your project created, make sure you have the KitKat SDK installed. Go to Tools > AndroidSDK Manager and make sure you have Android 4.4 (API 19) installed.

Android Studio will give you some boilerplate code to set up your application. Your project’s structure should look something like this:

Adding WebView to Your activity_main.xml file:

In order to add a WebView to the main activity’s layout.

1. Open the file activity_main.xml in the app/res/layout directory if it is not already open. Select the Text tab at the bottom of the activity_main.xml editor to see the XML markup.

This file defines the layout for your main activity, and the Preview panes show a preview of the activity. The Blank Activity layout doesn’t include any children. We’ll need to add the WebView.

2. In the XML pane, remove the ConstraintLayout elementand add the FrameLayout and the WebView as shown:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".Main">
        <WebView
            android:id="@+id/web_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbarAlwaysDrawHorizontalTrack="false"
            android:scrollbarAlwaysDrawVerticalTrack="false"
            android:soundEffectsEnabled="true" />
    </FrameLayout>   

3. To use the WebView you need to reference it in the Activity. Open the Java source file for the main activity, MainActivity.java  in the app/java/<PackageDirectory> directory. The following code in the OnCreate() method hooks up the Activity with the layout. The added lines create a new member variable, WebView, to refer to the WebView.

MainActivity.java
/* Create an instance of the WebView */
    WebView webView = null;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.webView = findViewById(R.id.web_view);
    }

Some warning messages in the margin of the editor will show up, because we haven’t imported the right classes for WebView yet. Luckily Android Studio can help you fill in the missing classes. The easiest way to do this is click and hover over an unknown class name and wait for a popup showing a “quick fix” — in this case, adding an Import statement for the WebView class.

The WebView is ready so let’s move forward to setting it up.

Enabling JavaScript:

JavaScript isn’t enabled by default in WebViews. To run a web application in the web view, you need to explicitly enable JavaScript by adding the following lines to the OnCreate method so it should look like this :

Enabling JavaScript
    WebView webView = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

        /* Enabling JavaScript */
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
    }  

An Import Statement of the WebSettings class should be added it’s the following: 

Load the Remote URL:

Your application needs permission to access the internet, if your application needs to load data from a remote URL.

1. In the manifests/AndroidManifest.xml we add the following line.

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

2. The next step is to call the loadUrl() method on the webview. Add the following line to the end of the onCreate method.

Now try running the project. If you don’t have a device handy, you can create an emulator (AVD or Android Virtual Device) by going to Tools > Android > AVD Manager.

In my case I tested it on my Android 19 device and this was the result:

Handling Navigation:

Try to click on any of the links available on the website for example try opening an other post. You’ll notice something strange that the app ends up opening the post in a browser and  that’s not what we want. So lets set handle the navigation to maintain the app working within our WebView.

Here’s the sequence of events:

  1. The WebView tries to load the original URL from the remote server, and gets a redirect to a new URL.
  2. The WebView checks if the system can handle a view intent for the URL, if so the system handles the URL navigation, otherwise the WebView will navigate internally (i.e. the user has no browser installed on their device).
  3. The system picks the user’s preferred application for handling an http:// URL scheme — that is, the user’s default browser. If you have more than one browser installed, you may see a dialog at this point.

In case you’re using a WebView just to display some simple web content (for example, a help page), this may be exactly what you need. However, for more advanced and sophisticated applications, you may want to handle the navigation links yourself.

To handle navigation inside the WebView you need to override the WebView’s WebViewClient, which handles various events generated by the WebView. You can use it to control how the WebView handles link clicks and page redirects.

The default implementation of WebViewClient makes any URL open in the WebView:

MainActivity.java
    /*Force links and redirects to open in the WebView instead of in a browser */   
    WebViewClientImpl webViewClient = new WebViewClientImpl(this);
    webView.setWebViewClient(webViewClient);

So right now Any URL will be opened in our WebView, but we only want to handle the links for our website while other URLs should be open in a browser.

To achieve this you need to extend the WebViewClient class and implement the shouldOverrideUrlLoading method. This method is called whenever the WebView tries to navigate to a different URL. If it returns false, the WebView opens the URL itself. (The default implementation always returns false, which is why it works in the previous example.)

Create a new class:

1. Right-click the java/package name of your app and select New > Java Class  

2. Enter MyAppWebViewClient as the class name and click OK

3. The MyAppWebViewClient.java file should look like this:

MyAppWebViewClient.java
 
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MyAppWebViewClient extends WebViewClient
{
    private Activity activity = null;

    public MyAppWebViewClient(Activity activity)
    {
        this.activity = activity;
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView webView, String url)
    {
        if(url.contains("http://www.dex-lab.com")) return false;
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        activity.startActivity(intent);
        return true;
    }
}

The new code defines MyAppWebViewClient as a subclass of WebViewClient and implements the shouldOverrideUrlLoading method.

The shouldOverrideUrlLoading method is called whenever the WebView is about to load a URL. This implementation checks if the URL contains the String “http://www.dex-lab.com/development/android/create-an-easy-webview-android-application/”. If the string exists, the mothod returns false, which tells the platform not to override the URL, but to load it in the WebView.

For any other hostname, the method makes a request to the system to open the URL. It does this by creating a new Android Intent and using it to launch a new activity. Returning true at the end of the method prevents the URL from being loaded into the WebView.

4. To use your new custom WebViewClient , add the following lines to your MainActivity class:

MainActivity.java
    /* Stop local links and redirects from opening in browser instead of WebView */
    MyAppWebViewClient webViewClient = new MyAppWebViewClient(this);
    webView.setWebViewClient(webViewClient);

Now, a user can click any of the links and stay within the app, but links to external sites are opened in a browser.

Handling Back Button

As you start playing around and navigating the awesome Infinite Coding articles, hitting the back button on Android exits the application, even though you’ve explored a few pages of the site.

WebView has a method canGoBack which tells you if there is anything on the page stack that can be popped. All you need to do is detect a back button press and determine if you should step back through the WebView’s history or allow the platform to determine the correct behaviour. Inside your MainActivity class, add the following method:

 

MainActivity.java
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && this.webView.canGoBack())
        {
            this.webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

And the WebView app should be fully functional right now. Hope you did learn from the tutorial and any questions or ideas will be welcomed just write them in the comments below.

Best reguards, Essia Mahmoudi

2 thoughts on “Create an easy WebView Android Application”

Leave a Comment

Your email address will not be published. Required fields are marked *