How To Add Download Listener To WebView In Kotlin

Introduction 

In this article, we will learn how to add a download listener to the download files from WebView in Android using Kotlin.

Coding Part

I have divided the coding part into 3 steps as shown in the following.
  1. Creating a new project with Kotlin support. 
  2. Setting up the project with Library. 
  3. Implementing the Download Listener with Kotlin. 
Step 1 - Creating a new project with Kotlin
  1. Open Android Studio and select "Create new project". 
  2. Name the project as per your wish and tick the "Kotlin checkbox support". 
  3. Then, select your Activity type (For Example - Navigation Drawer Activity, Empty Activity, etc.).
  4. Click the “Finish” button to create a new project in Android Studio.
Step 2 - Setting up the project with AndroidManifest
The following lines are added to your Kotlin project by default.
dependencies {   
    …  
   implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"  
   implementation 'com.android.support:appcompat-v7:26.1.0'  
   implementation 'com.android.support:support-annotations:26.1.0'  
   implementation 'com.android.support.constraint:constraint-layout:1.1.3'  
    …  
}
And also, we need to add the INTERNET/WRITE EXTERNAL STORAGE permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Step 3 - Implementation of Download Listener with Kotlin
  1. We need to add our WebView to our activity_main.xml file and initialize the WebView control. 
  2. Then, add the following lines.
    webview.loadUrl("http://cbseacademic.in/SQP_CLASSXII_2016_17.html")  
    webview.webViewClient = MyClient()  
      
    webview.setDownloadListener({ url, userAgent, contentDisposition, mimeType, contentLength ->  
        val request = DownloadManager.Request(Uri.parse(url))  
        request.setMimeType(mimeType)  
        request.addRequestHeader("cookie", CookieManager.getInstance().getCookie(url))  
        request.addRequestHeader("User-Agent", userAgent)  
        request.setDescription("Downloading file...")  
        request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType))  
        request.allowScanningByMediaScanner()  
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)  
        request.setDestinationInExternalFilesDir(this@MainActivity, Environment.DIRECTORY_DOWNLOADS, ".png")  
        val dm = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager  
        dm.enqueue(request)  
        Toast.makeText(applicationContext, "Downloading File", Toast.LENGTH_LONG).show()  
    })
    Here, we have to add the download manager request with media scanner to notify that the file is downloading.
  3. Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED is used to notify a user when the download is completed.
Full Code of MainActivity
You can find the full code implementation of MainActivty.kt in the following code.
class MainActivity : AppCompatActivity() {  
  
    @SuppressLint("SetJavaScriptEnabled")  
    override fun onCreate(savedInstanceState: Bundle?) {  
        super.onCreate(savedInstanceState)  
        setContentView(R.layout.activity_main)  
  
        webview.loadUrl("http://cbseacademic.in/SQP_CLASSXII_2016_17.html")  
        webview.webViewClient = MyClient()  
  
        webview.setDownloadListener({ url, userAgent, contentDisposition, mimeType, contentLength ->  
            val request = DownloadManager.Request(Uri.parse(url))  
            request.setMimeType(mimeType)  
            request.addRequestHeader("cookie", CookieManager.getInstance().getCookie(url))  
            request.addRequestHeader("User-Agent", userAgent)  
            request.setDescription("Downloading file...")  
            request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType))  
            request.allowScanningByMediaScanner()  
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)  
            request.setDestinationInExternalFilesDir(this@MainActivity, Environment.DIRECTORY_DOWNLOADS, ".png")  
            val dm = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager  
            dm.enqueue(request)  
            Toast.makeText(applicationContext, "Downloading File", Toast.LENGTH_LONG).show()  
        })  
  
    }  
  
    class MyClient : WebViewClient() {  
        override fun shouldOverrideUrlLoading(view: WebView, Url: String): Boolean {  
            view.loadUrl(Url)  
            return true  
  
        }  
    }  
  
    override fun onBackPressed() {  
        if (webview.canGoBack())  
            webview.goBack()  
        else  
            super.onBackPressed()  
  
    }  
}

Download Code:

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.

Share this

Related Posts

Previous
Next Post »

3 comments

comments
29 August 2019 at 13:11 delete

This is my first time i visit here and I found so many interesting stuff in your blog especially it's discussion, thank you. automatic text responder

Reply
avatar
20 September 2019 at 23:34 delete

We have sell some products of different custom boxes.it is very useful and very low price please visits this site thanks and please share this post with your friends. hoverwatch cost

Reply
avatar
4 October 2019 at 10:23 delete

Going sightseeing in Berat is truly an eye opener. The architecture and the wonderful combination of eastern and western cultures will leave you speechless. Albanian Museums

Reply
avatar

Please Comment about the Posts and Blog