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.
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.).
    Add Download Listener To Webview In Kotlin
  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.
  1. dependencies {
  2. implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
  3. implementation 'com.android.support:appcompat-v7:26.1.0'
  4. implementation 'com.android.support:support-annotations:26.1.0'
  5. implementation 'com.android.support.constraint:constraint-layout:1.1.3'
  6. }
And also, we need to add the INTERNET/WRITE EXTERNAL STORAGE permissions in AndroidManifest.xml.
  1. <uses-permission android:name="android.permission.INTERNET"/>
  2. <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.
    1. webview.loadUrl("http://cbseacademic.in/SQP_CLASSXII_2016_17.html")
    2. webview.webViewClient = MyClient()
    3. webview.setDownloadListener({ url, userAgent, contentDisposition, mimeType, contentLength ->
    4. val request = DownloadManager.Request(Uri.parse(url))
    5. request.setMimeType(mimeType)
    6. request.addRequestHeader("cookie", CookieManager.getInstance().getCookie(url))
    7. request.addRequestHeader("User-Agent", userAgent)
    8. request.setDescription("Downloading file...")
    9. request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType))
    10. request.allowScanningByMediaScanner()
    11. request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
    12. request.setDestinationInExternalFilesDir(this@MainActivity, Environment.DIRECTORY_DOWNLOADS, ".png")
    13. val dm = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
    14. dm.enqueue(request)
    15. Toast.makeText(applicationContext, "Downloading File", Toast.LENGTH_LONG).show()
    16. })
    Here, we have to add the download manager request with a media scanner to notify you that the file is downloading.
  1. 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.
  1. class MainActivity : AppCompatActivity() {
  2. @SuppressLint("SetJavaScriptEnabled")
  3. override fun onCreate(savedInstanceState: Bundle?) {
  4. super.onCreate(savedInstanceState)
  5. setContentView(R.layout.activity_main)
  6. webview.loadUrl("http://cbseacademic.in/SQP_CLASSXII_2016_17.html")
  7. webview.webViewClient = MyClient()
  8. webview.setDownloadListener({ url, userAgent, contentDisposition, mimeType, contentLength ->
  9. val request = DownloadManager.Request(Uri.parse(url))
  10. request.setMimeType(mimeType)
  11. request.addRequestHeader("cookie", CookieManager.getInstance().getCookie(url))
  12. request.addRequestHeader("User-Agent", userAgent)
  13. request.setDescription("Downloading file...")
  14. request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType))
  15. request.allowScanningByMediaScanner()
  16. request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
  17. request.setDestinationInExternalFilesDir(this@MainActivity, Environment.DIRECTORY_DOWNLOADS, ".png")
  18. val dm = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
  19. dm.enqueue(request)
  20. Toast.makeText(applicationContext, "Downloading File", Toast.LENGTH_LONG).show()
  21. })
  22. }
  23. class MyClient : WebViewClient() {
  24. override fun shouldOverrideUrlLoading(view: WebView, Url: String): Boolean {
  25. view.loadUrl(Url)
  26. return true
  27. }
  28. }
  29. override fun onBackPressed() {
  30. if (webview.canGoBack())
  31. webview.goBack()
  32. else
  33. super.onBackPressed()
  34. }
  35. }

Download Code

You can download the sample code from the following GitHub link.