Do you want to make an Android webview browser?

Don’t worry, I will help you to make a simple one.

Just like below.

webview android in example kotlin
Android WebView browser



Download Source Code – Kotlin & Java

In this post, you will learn more about WebView. Okay, let’s start…

What is Android WebView?

There may be occasions when you want to show a webpage to your users such as Terms and conditions, app manual or your website and so on.

In a traditional way, we can send users to an external web browser but there is no guarantee that users would come back. So that’s one of the main reasons Android introduced a widget named WebView.

As the name suggests it helps to show or view online and offline web pages in our app. It’s available in android.webkit package and has abilities in history management, zooming, javascript, and CSS rendering.

So you can load the webpage easily in your app,  webview will take care of it. It’s not a browser because it lacks navigational toolbar like features.

From the beginning to now, WebView has grown a lot. Let’s check how it implemented in Android.

WebView to Android System Webview – implementation history

WebView to Android System WebView -WebView implementation history
WebView to Android System WebView -WebView implementation history

WebView was added in API level 1. It renders web pages using Webkit engine, which behind Apple’s Safari browser. Actually, WebKit makes an environment or views for the webpage to display on the app.

In Android 4.4, For better performance, Google decided to change webview rendering from stock webview to google’s chromium or blink.

Lots of bugs and fixes through os update, that made long time vulnerable. So Android engineers innovated a separate Android System Webview app that can install and update through Google’s app market Play store with next release “Lolipop”.

That made easy fixes in less time.

In Android 7.0, there is no need to enable Android System Webview app, Chrome will take care of webview. if it is disabled or uninstalled already, the system will use android system webview.

If both of them get disabled, webview will use stock Webkit engine and take care of your valuable web pages.

How to add WebView to your layout?

Webview can easily be added to your layout as any other view. You can just drag and drop webview or write code for that just like below

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

You can use it as a root element or as a child element. While using as a root element don’t forget to add XML namespace.

How To Create WebView Programmatically In Android?

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.webkit.WebView

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
    
    //make a webview object
    val webview= WebView(this)
      //show it through setcontentview()method
    setContentView(webview)
        
    }
}

What is layout in Android?

For Kotlin users, I am using Android studio 3.1.2 and it uses Kotlin Android Extensions plugin by default.  So there is no need to call findviewByid and cast. just use the id of the widget and call the methods.

Make sure Android Studio has imported these lines

import kotlinx.android.synthetic.main.activity_main.*

Okay… Let’s start with our first example – Using the loadUrl() method.

Load Url – WebView Android Example In Kotlin & Java

android webview loadurl example
android webview loadurl example

We can easily load a webpage in webview using loadUrl() method. Just put your URL as a string, Before that, we must provide Internet permission in AndroidManifest.xml.


create a webview app in android with below code

package com.androidride.webviewloadurlex

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //loads androidride homepage to webview, webview: id of webview
        webview.loadUrl("https://www.androidride.com")
    }
}

https://youtu.be/uQngvrzzuDo

android system webview version
android system webview version

If you are testing webview code in devices which contains Android System WebView version below 43.0.2357.121 or below Lolipop. If anyone below happens

  1. server side redirect
  2. Click on links in WebView

Then it might lead to opening an external browser. To force open all links in WebView, we need to set WebViewClient.

webview.webViewClient = WebViewClient()

This is enough to open your links in webview. It internally calls, shouldOverrideUrlLoading() method and it returns false. False means redirect or clicking on a link opens in the same webview, True will abort the operation.

How to open link in the external browser using Android WebView

Sometimes You need to open your website links in webview and other links in external browsers. Then you can use the below sample code.

replace “www.example.com” with your site name.

 webview.webViewClient = object : WebViewClient()
        {

            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean
            {
                if(Uri.parse(url).host=="www.example.com")
                {
                    return false
                }

                val intent= Intent(Intent.ACTION_VIEW,Uri.parse(url))
                startActivity(intent)
                return true

            }
}

But shouldOverrideUrlLoading (WebView view, String url) was deprecated in API level 24. So if you are planning to make an application for Nougat or above, then you can use

public boolean shouldOverrideUrlLoading (WebView view,WebResourceRequest request)

To open links in WebView in All devices use both shouldOverrideUrlLoading() methods just like

webview.webViewClient = object : WebViewClient()
       {
           override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean
           {
               if(Uri.parse(url).host=="www.example.com")
               {
                   return false
               }

               val intent= Intent(Intent.ACTION_VIEW,Uri.parse(url))
               startActivity(intent)
               return true

           }

           @RequiresApi(Build.VERSION_CODES.N)
           override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean
           {
           val url=request?.url.toString()

               if(Uri.parse(url).host=="www.example.com")
               {
                   return false
               }
               val intent= Intent(Intent.ACTION_VIEW,Uri.parse(url));
               startActivity(intent)
               return true

           }
       }

How To Play YouTube Video In WebView By Enabling JavaScript In Android

Let’s open youtube in our webview.

Use our first example, and replace URL in loadUrl with “https://www.youtube.com” and run.

webview.loadUrl("https://www.youtube.com");

You may see these type of actions:

  1. Youtube shows a progress bar loading.
  2. Bowser says Please enable JavaScript in your browser.

This is because of JavaScript. If you are a web developer, you already know the importance of javascript. If you don’t, Javascript is a client-side programming language, it helps us to provide validation, animations and popups and so on.

By default, Javascript is disabled on your browser. we can easily enable it by simple lines of code.

how to enable javascript in android webview
how to enable javascript in android webview
//enables javascript in webview
      webview.settings.javaScriptEnabled = true

Now you can start watching youtube videos in your webview.

Android WebView local file example

android webview local file example
android webview local file example

In this example, you will learn how to show a local HTML file in webview. We have already created a webpage for you. You can use that for a sample.


<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Android webview local file ex - androidride</title>
<style type="text/css">
h1
{
border:2px solid #707cff;
padding:5px;
color:#707cff;
margin-top:120px;
text-align:center;
background-color:white;
}
p
{
text-align:center;
}
body
{
background-color:#e0e0e0;
}
</style>
</head>
<body>
<h1>ANDROIDRIDE</h1>
<p>
This is a <strong>local html file</strong> loaded from <strong>assets</strong> folder
</p>
</body>
</html>

This is a local html file loaded from assets folder

Just make an assets folder in your project, Right click on app->New->Folder->Assets Folder. Now a dialog appears to change the location of assets folder. Leave it and Click Finish.

Place demo.html into assets folder and use below code

package com.example.androidride.webviewlocalfileex

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
//loads local html file
        webview.loadUrl("file:///android_asset/demo.html")

    }
}

loadUrl() uses

LoadUrl() is a broad method and it works with:

    1. http:// and https:// URLs.

Eg: webview.loadUrl(“https://www.androidride.com”)
Webview.loadUrl(“//www.androidride.com”)

    1. Local filesystem URLs.

Eg: webview.loadUrl(“file:///storage/sdcard/index.html”)

Don’t forget to add


In your AndroidManifest.xml.

    1. Application assets and resources URLs.

eg:Webview.loadUrl(“file:///android_asset/demo.html”)

In URL, use android_asset not android_assets, yes, there is no ‘s’ at the end.

webview.loadUrl(“file:///android_res/mipmap/ic_launcher”)
There is no need for the file extension, but it won’t be a problem if you add it.

    1. content://URLs pointing content provider.

ERR_UNKNOWN_URL_SCHEME in Android WebView – Fixed.

err_unknown_url_scheme in android webview fixed
err_unknown_url_scheme in android webview fixed

In this example, You will learn how to solve ERR_UNKNOWN_URL_SCHEME in Android WebView. This type of error happens when WebView deals with UNKNOWN URL SCHEME links. Before that learn some basics.

What is URL SHEME?

The URL scheme is something before the colon in the URL. actually, it’s the protocol describes how to access the resource.

Scheme://host:port?path
eg: https://www.androidride.com:80/webview.html

WebView knows how to deal with HTTP, HTTPS, and file Schemes, but they don’t know what to do when these type of schemes come. ‘tel:’, ‘sms:’, and ‘mailto:’ and others.

So we have to tell webview to how to deal with those schemes in shouldOverrideUrlLoading() method. In this example, we are going to use ‘tel:’, ‘sms:’, ‘mailto:’, and ‘geo:’ links. When you click on them, each link will get opened with appropriate apps installed on your Android device.

demo.html

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>Error Unknown URL scheme fixed - androidride</title>
</head>
<body>
<a href='tel:99999999999'>Click here to call</a><br><br>
<a href='sms:99999999999'>Click here to message</a><br><br>
<a href='mailto:example@mail.com'>Click here to mail</a><br><br>
<a href='geo:51.5074,0.1278'>Click here to show location</a><br><br>
</body>
</html>
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.util.Log
import android.webkit.URLUtil
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        webview.webViewClient = MyWebViewClient()
        webview.loadUrl("file:///android_asset/demo.html")
    }

    inner class MyWebViewClient : WebViewClient()
    {
        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean
        {
            if(URLUtil.isNetworkUrl(url))
            {
                return false
            }
                try
                {
                val shareIntent= Intent()
                shareIntent.action=Intent.ACTION_VIEW
                shareIntent.data= Uri.parse(url)
                startActivity(shareIntent)
                }
                catch(e: ActivityNotFoundException)
                {
Toast.makeText(this@MainActivity, "Appropriate app not found", Toast.LENGTH_LONG).show()
                    Log.e("AndroidRide",e.toString())
                }
            return true
        }
        @RequiresApi(Build.VERSION_CODES.N)
        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean
        {
            val url=request?.url.toString()
            if(URLUtil.isNetworkUrl(url))
            {
                return false
            }
            try
            {
                val shareIntent= Intent()
                shareIntent.action=Intent.ACTION_VIEW
                shareIntent.data= Uri.parse(url)
                startActivity(shareIntent)
            }
            catch(e: ActivityNotFoundException)
            {
Toast.makeText(this@MainActivity, "Appropriate app not found", Toast.LENGTH_LONG).show()
                Log.e("AndroidRide",e.toString())
            }
            return true

        }

    }
}

      • If it’s a network URL, WebView force the links to open in WebView,otherwise find a best option from Android System.

Create your webview app with the above code or you can download our example.

WebView loadData() example in Android

In this Android WebView example, we will show you how to render HTML code in Android WebView. It’s simple, Android API provides a method called loadData().

loadData() method needs 3 contents.

      1. String htmlData: This is our html content.
      2. String mimeType: here we use “text/html”.
      3. String encoding: most of the time, base64 or UTF-8.
      • It works with data,http and https schemes.
      • If you use other schemes, webview can’t access content due to javascript same origin policy.
      • You should use loadDataWithBaseURL(), if you want to use other schemes.
class MainActivity : AppCompatActivity()
{

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val html="




Hi, AndroidRide

" webview.loadData(html,"text/html","UTF-8") } }
webview loaddata example
webview loaddata example in android

WebView loadDataWithBaseURL() example in Android

In this example, you will learn how to work with loadDataWithBaseURL() example. When you want to fetch an image from the assets folder using loadData() method. JavaScript origin policy restricts the access to content.

loadDataWithBaseURL() avoids this problem by specifying BaseURL. Using the Base URL, system resolve relative URLs in HTML content.

loadDataWithBaseURL() needs

  1. String baseURL: This URL is used to resolve relatvie URLs.
  2. String data: Html content that you want to show.
  3. String mimeType: mimeType of HTML data
  4. String encoding: encoding of html data
  5. String historyURL: This URL loads when you navigate back in webview

In this example, I am going to use the same loadData() code but just want to add image ‘ic_launcher’ from the mipmap folder.

class MainActivity : AppCompatActivity()
{

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val html="




Hi,AndroidRide

" webview.loadDataWithBaseURL("file:///android_res/mipmap/",html,"text/html","UTF-8",null) } }
loaddatawithbaseurl example
android webview loaddatawithbaseurl example

Android WebView Download File example

android webview download file example
android webview download file example

In this android webview example, you will learn how to download a file using WebView and DownloadManager. Using DownloadManager, we can reduce code and leave the stress to DownloadManager. We also show AlertDialog for Download notification.

You can download the file using AsyncTask too.

Create a webview app project in Android Studio, Add below lines to AndroidManifest.xml



    

Use below code

package com.example.androidride.webviewdownloadfileex

import android.Manifest
import android.app.DownloadManager
import android.content.Context
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AlertDialog
import android.webkit.CookieManager
import android.webkit.URLUtil
import android.webkit.WebViewClient
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        webview.loadUrl("https://www.google.com")
        webview.webViewClient = WebViewClient()

        webview.setDownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
            //checking Runtime permissions
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            {
                if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    //Do this, if permission granted
                    downloadDialog(url, userAgent, contentDisposition, mimetype)

                } else {

                    //Do this, if there is no permission
                    ActivityCompat.requestPermissions(
                        this,
                        arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                        1
                    )

                }
            } else {
                //Code for devices below API 23 or Marshmallow
                downloadDialog(url, userAgent, contentDisposition, mimetype)

            }
        }
    }

    fun downloadDialog(url:String,userAgent:String,contentDisposition:String,mimetype:String)
    {
        //getting file name from url
        val filename = URLUtil.guessFileName(url, contentDisposition, mimetype)
        //Alertdialog
        val builder = AlertDialog.Builder(this@MainActivity)
        //title for AlertDialog
        builder.setTitle("Download")
        //message of AlertDialog
        builder.setMessage("Do you want to save $filename")
        //if YES button clicks
        builder.setPositiveButton("Yes") { dialog, which ->
            //DownloadManager.Request created with url.
            val request = DownloadManager.Request(Uri.parse(url))
            //cookie
            val cookie = CookieManager.getInstance().getCookie(url)
            //Add cookie and User-Agent to request
            request.addRequestHeader("Cookie",cookie)
            request.addRequestHeader("User-Agent",userAgent)
            //file scanned by MediaScannar
            request.allowScanningByMediaScanner()
            //Download is visible and its progress, after completion too.
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            //DownloadManager created
            val downloadmanager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
            //Saving file in Download folder
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,filename)
            //download enqued
            downloadmanager.enqueue(request)
        }
        //If Cancel button clicks
        builder.setNegativeButton("Cancel")
        {dialog, which ->
            //cancel the dialog if Cancel clicks
            dialog.cancel()
        }

        val dialog:AlertDialog = builder.create()
        //alertdialog shows
        dialog.show()

    }
}


How To Run JavScript In Android WebView

how to run javascript in android webview
how to run javascript in android webview

I already said JavaScript has an important role in the web world. In Android, we can also make use of JavaScript by sending data to Javascript from Android and vice versa. But it also raises security issues too. If you are using any third-party code, make sure it’s not vulnerable to users security.

Android API provides a number of methods and classes to achieve a super web app. I have categorized them

JavaScript calling Kotlin/Java

      1. addJavascriptInterface()
      2. WebMessagePort – (6.0)

Kotlin/Java calling JavaScript

      1. loadUrl()
      2. evaluateJavascript() – (4.4)
      3. WebMessage – (6.0)

The numbers shown in the brackets means the starting API. We are not going to discuss WebMessagePort and WebMessage here. That will be updated later.

webview addJavascriptInterface example in android

webview addjavascriptinterface
webview addjavascriptinterface example in android

In this addJavascriptInterface example, we send a message from a local HTML webpage to Android and show it through a toast.

JavaScript can access methods in API level Build.VERSION_CODES.JELLY_BEAN_MR1 and above, if they are

      • defined as public
      • annotated with JavascriptInterface

sample.html

WebView addJavascriptInterface Example





Web To Android

MainActivity.kt

class MainActivity : AppCompatActivity()
{
    @SuppressLint( "SetJavaScriptEnabled")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //webview loads sample html
        webview.loadUrl("file:///android_asset/sample.html")
        //enables javascript in webview
        webview.settings.javaScriptEnabled = true
        //injecting java object
        webview.addJavascriptInterface(JavascriptInterface(),"javascript_object")
    }

    private inner class JavascriptInterface
    {
        @android.webkit.JavascriptInterface
        fun showToast(text: String?)
        {
            //toasting the text
            Toast.makeText(this@MainActivity,text,Toast.LENGTH_SHORT).show()
        }
    }

    override fun onDestroy()
    {
        //removes the java object from webview
        webview.removeJavascriptInterface("javascript_object")
        super.onDestroy()
    }
}


how above code works?

      • JavaScript enabled.
      • Inject java object into webpage using addJavascriptInterface() method. It needs
        1. Java class object: The java class object which inject into webview
        2. String name: The name used to access java methods from JavaScript
        3. It’s better to remove java object from webview after the use

WebView evaluateJavascript example in Android

evaluatejavascript android

Let’s call javascript from Java. In this example, we receive the text from edittext and send it to the local HTML page. Use loadUrl() for below 4.4 and evaluateJavascript() works with KitKat and above.

sample.html

Android Javascript Ex




WebView

MainActivity.kt

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //loads sample html
        webview.loadUrl("file:///android_asset/sample.html")
        //enables javascript in webview
        webview.settings.javaScriptEnabled = true
    }

    fun sendMessage(view: View?)
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        {
            //calls when version code greater than or equal to KITKAT
            webview.evaluateJavascript("show(\"" + edittext.getText() + "\")",null)
        }
        else
        {
            webview.loadUrl("javascript:show(\"" + edittext.getText() + "\")")
        }
    }
}


Android WebView Browser example – Progress bar included

Finally, we are here. Let’s create a webview app browser. This browser has

      • ProgressBar support
      • Google search and load URL support
      • Download file support
      • YouTube video support
      • Navigate history and custom home page
      • Share Support

open your Android Studio.

Step 1

Start a new Android Studio project.

Application Name: WebView Browser
Company Domain: androidride.example.com

Check Include Kotlin Support.


Step 2

Select form factors and minimum SDK

Select API 15: IceCreamSandwich and Click Next.


Step 3

Add Empty activity to Project.


Step 4

Add INTERNET and WRITE_EXTERNAL_STORAGE permission in AndroidManifest.xml

AndroidManifest.xml



    
    
    
        
            
                

                
            
        
    


      • android:windowSoftInputMode=”stateAlwaysHidden|adjustNothing” – it helps by without adjusting our bottom bar layout and disable the focus in EditText while startup.

Step 5

build.gradle
apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.androidride.webviewbrowser_kotlin"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    testImplementation 'junit:junit:4.12'
    }

Step 6

Colors.xml


    #707cff
    #3250cb
    #ffa7b7
    #e0e0e0
    #1d1d1d

Step 7

Styles.xml
    
    

 



Step 8

activity_main.xml


    

        
            

            

            


    

    

    

    

        

        

        

        

        

    




      • android:layout_weight attribute used to hold widgets.
      • android:inputType=”textNoSuggestions” disable spell check
      • android:background=”?android:selectableItemBackground” – makes transparent

I have used vector asset icons, you can also access them by right clicking on res->New->Vector Asset->Click on clip Art and select your icons, you can change color and size. Click OK and Next.


Step 9

custom_progress.xml



    
        
            
                
                
            
        
    

    
        
            
                
                
            
        
    


Step 10

This browser has a simple home page, for that, we have to add local HTML file in the assets folder.

demo.html
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Android webview local file ex - androidride</title>
<style type="text/css">
h1
{
border:2px solid #707cff;
padding:5px;
color:#707cff;
margin-top:120px;
text-align:center;
background-color:white;
}
body
{
background-color:#F2F2F2;
}
</style>
</head>
<body>
<h1>ANDROIDRIDE</h1>
</body>
</html>

Step 11

MainActivity.kt
package com.example.androidride.webviewbrowser_kotlin

import android.annotation.SuppressLint
import android.app.Activity
import android.app.DownloadManager
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.support.v7.app.AlertDialog
import android.view.KeyEvent
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
import android.util.Patterns
import android.view.inputmethod.InputMethodManager
import android.webkit.*

class MainActivity : AppCompatActivity()
{
var share_url:String? = null

    @SuppressLint("SetJavaScriptEnabled")
    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //loads local demo html file
		webview.loadUrl("file:///android_asset/demo.html")
        //toolbar set as actionbar
        setSupportActionBar(toolbar)
        //javascript enabled
        webview.settings.javaScriptEnabled = true
		
		//downloadlistener enabled
       webview.setDownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
            //checking Runtime permissions
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            {
                if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    //Do this, if permission granted
                    downloadDialog(url, userAgent, contentDisposition, mimetype)

                } else {

                    //Do this, if there is no permission
                    ActivityCompat.requestPermissions(
                        this,
                        arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                        1
                    )

                }
            } else {
                //Code for devices below API 23 or Marshmallow
                downloadDialog(url, userAgent, contentDisposition, mimetype)

            }
        }    





        webview.webChromeClient = object : WebChromeClient()
        {
            override fun onProgressChanged(view: WebView?, newProgress: Int)
            {
                //it calls when progress changed
                progressbar.progress=newProgress
                super.onProgressChanged(view, newProgress)

            if(newProgress==100)
            {
                //if progress completes, progressbar gets hidden
                progressbar.visibility = View.GONE
            }

            }


            override fun onReceivedIcon(view: WebView?, icon: Bitmap?) {
                super.onReceivedIcon(view, icon)
                //favicon of webpage
                //toolbar_search_imageview_favicon.setImageBitmap(icon)
            }
        }

        webview.webViewClient = object: WebViewClient()
        {
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?)
            {
                //it calls when webpage gets started and shows ProgressBar.
                progressbar.visibility = View.VISIBLE
				
				if("file:///android_asset/demo.html" != url)
				{
                    //if url is demo html url, then don't set to edittext
                edit_text.setText(url)
				}
				else
				{
                    //edittext cleared
				edit_text.text.clear()
				}

                super.onPageStarted(view, url, favicon)
            }

            override fun onPageFinished(view: WebView?, url: String?)
            {
                //if webpage gets finished
                share_url=url

                super.onPageFinished(view, url)
            }

        }

    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean
    {
        //when back button taps
        if(keyCode == KeyEvent.KEYCODE_BACK && this.webview.canGoBack())
        {
            webview.goBack()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    fun goBack(view:View?)
    {
        //webview goes to previous page if there is one.
        if(webview.canGoBack())
            webview.goBack()
    }

    fun goForward(view: View?)
    {
        //webview goes to forward page if there is one.
        if(webview.canGoForward())
            webview.goForward()
    }

    fun goHome(view:View?)
    {
        webview.loadUrl("file:///android_asset/demo.html")
		}

    fun refresh(view: View?)
    {
        //it reload the current page
        webview.reload()
    }

    fun share(view: View?)
    {
        //Intent created
        val shareIntent = Intent()
        shareIntent.action=Intent.ACTION_SEND
        shareIntent.type="text/plain"
        //url of the sharing page
        shareIntent.putExtra(Intent.EXTRA_TEXT,share_url)
        shareIntent.putExtra(Intent.EXTRA_SUBJECT,"URL")

        startActivity(Intent.createChooser(shareIntent,"Share with your friends"))

    }

    fun go(view:View?)
    {
        //get text from edittext
     var text=edit_text.text.toString()
        searchOrLoad(text)
    }

    fun searchOrLoad(text:String)
    {
        //checks if it's a url or a string
        if(Patterns.WEB_URL.matcher(text.toLowerCase()).matches())
        {
            if (text.contains("http://") || text.contains("https://"))
            {
                webview.loadUrl(text)
            }
            else
            {
                webview.loadUrl("http://$text")
            }
        }
        else
        {
            //google search url
            webview.loadUrl("https://www.google.com/search?q=$text")
        }

        hideKeyboard()


        }

    private fun hideKeyboard()
    {
        //INPUTMETHODMANAGER service created.
        val inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as  InputMethodManager
        //it hides softkeyboard
        inputMethodManager.hideSoftInputFromWindow(currentFocus.windowToken,InputMethodManager.SHOW_FORCED)
     }

    override fun onPause()
    {
        super.onPause()
        webview.onPause()
        webview.pauseTimers()
    }

    override fun onResume() {
        super.onResume()
        webview.onResume()
        webview.resumeTimers()
    }

fun downloadDialog(url:String,userAgent:String,contentDisposition:String,mimetype:String)
    {
        //getting file name from url
        val filename = URLUtil.guessFileName(url, contentDisposition, mimetype)
        //Alertdialog
        val builder = AlertDialog.Builder(this@MainActivity)
        //title for AlertDialog
        builder.setTitle("Download")
        //message of AlertDialog
        builder.setMessage("Do you want to save $filename")
        //if YES button clicks
        builder.setPositiveButton("Yes") { dialog, which ->
            //DownloadManager.Request created with url.
            val request = DownloadManager.Request(Uri.parse(url))
            //cookie
            val cookie = CookieManager.getInstance().getCookie(url)
            //Add cookie and User-Agent to request
            request.addRequestHeader("Cookie",cookie)
            request.addRequestHeader("User-Agent",userAgent)
            //file scanned by MediaScannar
            request.allowScanningByMediaScanner()
            //Download is visible and its progress, after completion too.
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            //DownloadManager created
            val downloadmanager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
            //Saving file in Download folder
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,filename)
            //download enqued
            downloadmanager.enqueue(request)
        }
        //If Cancel button clicks
        builder.setNegativeButton("Cancel")
        {dialog, which ->
            //cancel the dialog if Cancel clicks
            dialog.cancel()
        }

        val dialog:AlertDialog = builder.create()
        dialog.show()

    }

}

Hey… Thanks for scrolling. If you find anything useful in this post, please share it.

Conclusion

WebView has an important role in Android programming. With a few lines of code, beginners can also easily load web pages in their app. You have learned to download the file and run javascript using Android WebView. I am sure that these examples make you better dealing with WebView. This is a small guide about WebView. You can also find more information from below links.

Please disable your adblocker or whitelist this site!