What is An Android WebView? How to Choose The Best Webview App?

Android WebView is a powerful tool for displaying web pages on mobile devices.

A WebView is a component of the Android operating system that allows applications to display content from the Internet.

Therefore in its simplest terms, WebView allows you to display website content on your device.

It’s used by all kinds of apps as a way to display rich content like text, videos or images, or chat services.

You may have heard about the new Google Chrome browser for Android.

But there are other ways to view websites on your phone or other devices.

There is only one type of WebView available for Android developers which comes with a chrome app or you can use the Google Play WebView library.

But it needs a chrome application that must be installed on the device to run the WebView application.

And here, we’ll cover the basics of creating a WebView application.

 

What is an Android WebView App?

WebView is used by many apps on Android devices to display information from websites.

They are a part of the Android operating system and they allow an app to display content from the internet.

This includes text, images, and even videos and other content from the web.

These views are part of the operating system and not something that developers need to implement themselves.

If you’re building an application, you can use these views to display content from the net without having to write any line of code yourself.

 

How to Create an Android WebView App?

This project is divided into two parts. The first one will tell you to create a fairly simple Webview app that will just show a website in it.

The second part will describe you make changes to a website while it displays in the WebView. This leads to some complex programming knowledge of Android and a good hand in Javascript language as well. We will write the Android WebView program and to make changes or get data from the website, require to write the code in JavaScript language.

Note: Please keep in mind, that the Webview app will only work correctly. When the Chrome app is installed on the device. Else it will show as an ordinary browser.

Open the Android Studio software and create a new project. Use the latest version of the Gradle and Gradle plugin. Because it will make your work a lot easier as a developer. Android studio and gradlew will tell you to exact errors instead of a vague long text message.

I m using the JAVA language for this project. In the next update, I will write the KOTLIN language program. Both will be available.

 

Frist Part: Start With Basic Webview App

When the new project is built successfully. I know it takes some time from a few seconds to minutes depending on the internet speed and the cache version of the gradlew in your system.

Open the layout file of the Activity MainActivity, If you did not change the name of the activity. Add the Webviw in it. Use the match_parent for height and width. Also, write the id webiewof it, you can write the id as you like.

Your webview will look like this

	<android.webkit.WebView
		android:id="@+id/webView"
		android:layout_width="match_parent"
		android:layout_height="match_parent" 
		/>

 

By default, there no permission has been assigned by Android to the app. We need to give Internet permission to our app. To do this, we need to write android.permission.ACCESS_NETWORK_STATE and android.permission.INTERNET Your manifest file must contain these codes to access the internet.

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

Now go back to the Activity. declare the WebView webview before the onCreate of the activity to make it accessible anywhere in the activity.

Get the Webview from its id that was webiew in the layout. For example webview = findViewById(R.id.webview);

It’s time to load the website in the Android WebView . Just copy the URL of the page that you want to see in the app. Use the loadUrl method of WebiView

Your code will be like this

	WebView webview =  findViewById(R.id.webview);
	webview.loadUrl("your_websiite_url.com");	

 

Now run the app in an emulator or real device. please go through the documentation of Android, To know about how to run the emulator or attach the mobile device in the Android Studio. You will see the website displayed in full width and height of website without the URL bar of the browser. This is your first and basic web view app.

We did not attach the listener and chromeClient to the website to know the events. Basically, there are two kinds of listener that is important for the app those are setDownloadListener and setWebViewClient listener.

The setDownloadListener is used to create your own file download manager. You can set the location of the file, set the sticky notification in the notification tray, show a toast message, or download the file percentage.

The setWebViewClient tell us about the web page loading events. It has some good methods. A website is created using various libraries, JS, and CSS files. Every file and library has its own URL. The shouldInterceptRequest method tells us what current URL is loading.

shouldOverrideUrlLoading this method trigger before the page is triggered onReceivedError .

I m going to give you an example of a listener so you can update them according to your requirement. I have written the comment in the methods for your understanding. So you can use them accordingly. You must remove the comment or add the comment above the method like I do every method. I included the deprecation methods just to make sure our app will run smoothly when it is installed and opens in older versions of android like Android 4 or below.

        webView.setWebViewClient(new WebViewClient() {

            @SuppressWarnings("deprecation")
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String tempUrl) {
                // To Do: Check if the browser can handle the loading url then leave it. Otherwise allow the OS to handle things like tel, mailto, etc.
				// Also if you want to stop some specific url loading then here you can do it.
                return true;
            }

            @TargetApi(android.os.Build.VERSION_CODES.N)
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                // To Do: Check if the browser can handle the first loading url then leave it. Otherwise allow the OS to handle things like tel, mailto, etc.
				// Also if you want to stop some specific url loading then here you can do it.
				
                return true;
            }

            // Handle API until level 21
            @SuppressWarnings("deprecation")
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                return null;
            }

            /**
             * here we will intercept the request and add all necessary header to all resource request too
             * request.getUrl()
             * mMethods.returnHeaders()
             * Handle API 21+
             *
             * @param view
             * @param request
             * @return
             */
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
				// Intercept the ongoing loading url when a web page is opening. The developer uses this method to intercept the url and its header. Change the header of the url and send it back to webview.
				// return WebResourceResponse, if you made changes to the header of the url or if anything else has been done. Else return null to leave it.
                return null;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
				// know which page url is going to load into webview
            }

            @Override
            public void onPageFinished(WebView view, String url) {
				// trigger when a web page completely load in the webview.
                super.onPageFinished(view, url);
            }

            @SuppressWarnings("deprecation")
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
				// webpage Javascript shows their errors in browser console. to simulate the console. It will show you all kind of JS error. 
				// this deprecation method will trigger when theh your app installed in older version of android.
				
            }

            @TargetApi(android.os.Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
				// webpage Javascript shows their errors in browser console. to simulate the console. It will show you all kind of JS error. 
                
				onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
            }
        });

 

Part 2: Writing A Advanced WebView Android App

In Part 1, we created a simple app that displays the webpage. In this part, we will go to create an app that can be used to upload to Google Play Store. Let’s start.

Here is the list of functionalities of our app and we are going to write a program for it.

  • Internet is available or not.
  • Adding Pull to down refresh the web page.
  • Setting own user agent.

There is two way to know whether the net is working on a device using data or wifi. The first one is, SERVICE, and second is to know the status of the net every time whenever a new page is going to load in WebView.

With SERVICE or Receiver, running in the background process of an android app can tell us net is working or not. A listener will be set in Activity that will return the status of the Internet.

Here is only one problem or catch. All kinds of services are stopped or killed by Android OS or another app. Android OS kills the service on various events like the battery is low and the user activates the battery saver mode, the device is switched off or restarted, App killed, and services are also killed by the memory cleaner app or another app. The important thing is that developer should know when the service is killed and restarted. Or keep checking service is running or not.

To create the service using the in-builtBroadcastReceiver class. Create a Java class named InternetChecking and implemnet BroadcastReceiver . It has the onRecieve method. it is called every time whenever a change of internet status is detected by the Android operating system.

public class InternetChecking extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        try
        {
            if (isOnline(context)) {
                dialog(true);
                Log.e("status", "Online Connect Intenet ");
            } else {
                dialog(false);
                Log.e("status", "Conectivity Failure !!! ");
            }
        } catch (NullPointerException e) {
			dialog(false);
			Log.e("status", "Conectivity Failure !!! ");
            e.printStackTrace();
        }
    }

    private boolean isOnline(Context context) {
        try {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            //should check null because in airplane mode it will be null
            return (netInfo != null && netInfo.isConnected());
        } catch (NullPointerException e) {
            e.printStackTrace();
            return false;
        }
    }
}

The next step is to registred Receiver in Manifest and binds it in our Activity class. We will add the By InternetChecking class in the receiver that we are going to register in the manifest file. it is easy to bind the receiver with the Activity class. So that our activity will receive the updated status of the net and our app will behave like that.

Add this code to the manifest file

	<receiver
		android:name=".InternetChecking"
		android:exported="false"
		tools:node="merge">
		<intent-filter>
			<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
			<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
		</intent-filter>
	</receiver>

NOTE: The code tools:node="merge" only include in the receiver when your app is targeting android api 31 and above. else there is no use of it. you can safely remove this code.

The intent-filter is used to tell the receiver what kind of message should be received by Android OS. Here we wrote the CONNECTIVITY_CHANGE and WIFI_STATE_CHANGED. Both return the internet status in android.

	
	// write the code in onCreate of the activity
	InternetChecking mNetworkReceiver = new InternetChecking();
	
	
    // call it to register the receiver with activity
	private void registerNetworkBroadcastForNougat() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
        }
    }

	// un register the broadcastreciever to free the memory to avoid the memory leak problem
    protected void unregisterNetworkChanges() {
        try {
            unregisterReceiver(mNetworkReceiver);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }

Although the use of service is recommended these days, the app developer should implement the manual internet checking method. It will work when there is no response from the service.

It is easy to know the status of Intenet on the android device. You need to create the object of ConnectivityManager the class and get the Intenet status by calling

getActiveNetworkInfo().isConnected(). It will return the status of the internet in boolean. True means the internet is working and false means it does not.

 

	private boolean isNetworkConnected() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
	}

 

Adding Pull to down refresh the web page.

A library called Android swipeLayout will be used to integrate the pull-down to refresh the web page. First, we need to add the library in the app-level build.gradle file. Use the latest version of library 1.1.0. write the below code in the build.gradle file

    
	implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'

Sync the project. After successfully syncing, this library will add to your project. Let’s add the swipe layout to the layout XML file. Open the layout file of Activity. Add the Webview into the Swipelayout. Your layout file looks like this.

    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/swipeContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        >
		<webview.android.utility.VideoEnabledWebView
			android:id="@+id/webView"
			android:layout_width="match_parent"
			android:layout_height="match_parent" />

    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

NOTE: i wrote the app:layout_behavior="@string/appbar_scrolling_view_behavior" It will take care of scroll events of both swipelayout and webview.

Now open the activity file, and get the swipelayout. Writ this code SwipeRefreshLayout mySwipeRefreshLayout = this.findViewById(R.id.swipeContainer); in the activity.

We need to disable the swipelayout to stop calling the refresh event until the page is completely loaded in the webview. Else webpage and swipelayout will not load the page ever. in webviewClient listener, in onPageFinished write the below code to stop the refresh event of swipelayout while loading the web page.

	
	@Override
	public void onPageStarted(WebView view, String url, Bitmap favicon) {
		//.... your code here 
		mySwipeRefreshLayout.setEnabled(false);
		mySwipeRefreshLayout.setRefreshing(true);
	}

 

When the web page load is completed. We need to make the swipelayout refreshable. in the onPageFinished method write the below code

	
	@Override
	public void onPageFinished(WebView view, String url) {
		//.... your code here 
		mySwipeRefreshLayout.setEnabled(true);
		mySwipeRefreshLayout.setRefreshing(false);
	}

Till android 9, the webview will work perfectly, and the scroll will be done smoothly. But in android 10 and above, in some android devices, there is a scrolling issue. To overcome we need to add the onScroll listener on the swipelayout to know webview has reached the top of the page or not. And then trigger the refresh event.

Setting own user agent.

The user agent in the browser is used to tell the browser how to treat the web page. Load the webpage in desktop version or mobile version. Or is it just a robot or any kind of script?

By default, android uses the mobile view user agent to tell the browser to show the web page in the mobile view layout. But Android has given a setting to set own

	
	webvieew.getSettings().setUserAgentString("user_agent_string");

 

Please keep in mind that do not try to create your own user agent. Either website will load incorrectly or end up with functionality errors. Today User-agent used by modern browsers is created by an international organization. Here is the list of browser user agents to copy from.

Ask for permission for the Camera, file upload, GPS, and other things

Last but not least. Some websites need special permission to run properly. For example, the Website that hosts the streaming services need the camera and voice recording permission, the website that delivers the items looks for the GPS location of customers, on form submission sites, the user needs to upload the files, etc.

By default Android version 5, this permission was taken when the user is going to install the app. But in Android version 6 and above, the developer should implement run time permission, and take the permission from the user by showing an in-built popup.

Adding the chromeClient listener, the developer will know which permission is requested by a website and handle it accordingly.

 

Best Android WebView App of 2022

Most Native Apps development costs thousands of dollars for Android development.

But thanks to Android WebView App, these apps serve similar purposes as Android apps.

The purpose of Android WebView is the bring out a lookalike app in Google Play Store.

Because it is very cost-effective for businesses and e-commerce store owners who are looking for generating extra traffic and leads through apps.

However, as the name suggests Android WebView apps aren’t native apps.

Some of these WebView apps are discussed below

1) Obit Android WebView App

Obit WebView Android App is an application that helps in creating an Android App for your website.

These apps are named WebView because the webpages are viewed on mobile devices as responsive pages.

It only helps you to publish your app on the play store and configure it seamlessly

It takes 5 min to configure the app and no programming knowledge is required

Features of the Obit Android WebView Apps are:

  • Push Notification
  • Previous Push Message List
  • Social Links
  • Hide Elements on Page
  • Work With All Kinds of  Website
  • Change Splash Screen Images
  • User Agent
  • List of Devices

2) Web URL to Android App Converter

This is an android WebView app using Kotin where you can convert your website URL to an android app.

It is an android app that is constructed with many features such as:

  • File and digital digicam uploads
  • Qr code scanner API
  • Splash screen
  • URL Handling
  • Media downloader
  • Clever offline fallback
  • Dark mode
  • Intriguing customizable UR
  • Fully Customizable Code
  • No internet mangement
  • Email Intent for Direct Open Email application etc.

3) Smart Android WebView App Template

Smart Android WebView App is a WebView Mobile Application that supports all responsive websites to full load on mobile devices. With this And4roid App Template now you can easily convert your responsive website into Android App. The package contains complete source code with clean code that is easy to understand and implement. Some of the features of this product are:

  • HTML5, JavaScript Video
  • Beautiful UI
  • Clean & Customizable Code
  • Download Manager & File Upload
  • Privacy Policy
  • About Us
  • Reload, Forward, Backward
  • Swipe to refresh
  • About Us Screen
  • Navigation Drawer
  • Admob Ads
  • One Signal Push Notification
  • Floating Action Button
  • Social Media Enabled
  • Error screen in case of no Internet

4) Web OS: Cross Platform Web View App Template

WebOS is a React Native mobile app based on WebView. WebOS is integrated with JSON files that can be easily edited to configure the App. You don’t need to edit the main app code unless you need to add more features. This WebOS APP template uses the latest version of React Native & Expo SDK. So using this same app template you render both Android and IOS apps at the same time. You don’t need to buy any extra app template for android or IOS.

Some of the features of this product are:

  • Google Material Design
  • Easy configuration using JSON File
  • Well Documentation
  • Splash Screen
  • RTL Supported
  • Responsive Design
  • Admob Support
  • Audience Network Support
  • One-Click Push Notification
  • Page Error and Offline Handling
  • Clean Code with useful comments
  • Supports Downloading, Uploading files

5) Bizzy: Android Multi-Purpose Web View App

Bizzy is a universal app with WebView + website templates that display business portfolios, team members, services, and mobility information.

The app has a built-in WebView that allows you to view responsive websites simply by editing a line of code.

The package comes with a fully responsive website template, so all you have to do is edit the HTML and CSS files, upload them to your own hosting server, and set the path to your app’s configuration file.

You can also send push notifications to all registered devices.

Features of the product include:

  • Android Studio 3. x project – Universal
  • Android 5.0+
  • AdMob banners
  • Parse Push Notifications with back4app
  • Fully Responsive website template included, based on Bootstrap
  • contact_me.php file included allowing users to email you via the contact form
  • PDF User Guide included
  • PSD icon graphics included
  • Easy to customize, well-commented code

 

Conclusion:

Android WebView App helps businesses and e-commerce brands to launch their mobile app seamlessly.

Therefore Small and medium enterprises can take the benefit of the app by implementing this cost-effective application.

Normally native android apps cost thousands of dollars and it is only effective to launch such apps if there is large growing traffic on your website.

But if you are just starting out you really don’t really have to spend that big amount on a native app.

This is where Android WebView App helps small and medium enterprises to launch an Android App using WebView technology.

However, the mobile apps development team at TMD develops various native android apps.

If you have any requirements on native android apps contact us at [email protected]

 

Leave a comment

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