How To Add Download Listener To WebView In Kotlin

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.
  • Creating a new project with Kotlin's support.
  • Setting up the project with the Library.
  • 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.).
     
    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.     …  
  3.    implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"  
  4.    implementation 'com.android.support:appcompat-v7:26.1.0'  
  5.    implementation 'com.android.support:support-annotations:26.1.0'  
  6.    implementation 'com.android.support.constraint:constraint-layout:1.1.3'  
  7.     …  
  8. }  
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.   
    4. webview.setDownloadListener({ url, userAgent, contentDisposition, mimeType, contentLength ->  
    5.     val request = DownloadManager.Request(Uri.parse(url))  
    6.     request.setMimeType(mimeType)  
    7.     request.addRequestHeader("cookie", CookieManager.getInstance().getCookie(url))  
    8.     request.addRequestHeader("User-Agent", userAgent)  
    9.     request.setDescription("Downloading file...")  
    10.     request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType))  
    11.     request.allowScanningByMediaScanner()  
    12.     request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)  
    13.     request.setDestinationInExternalFilesDir(this@MainActivity, Environment.DIRECTORY_DOWNLOADS, ".png")  
    14.     val dm = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager  
    15.     dm.enqueue(request)  
    16.     Toast.makeText(applicationContext, "Downloading File", Toast.LENGTH_LONG).show()  
    17. })  
    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.   
  3.     @SuppressLint("SetJavaScriptEnabled")  
  4.     override fun onCreate(savedInstanceState: Bundle?) {  
  5.         super.onCreate(savedInstanceState)  
  6.         setContentView(R.layout.activity_main)  
  7.   
  8.         webview.loadUrl("http://cbseacademic.in/SQP_CLASSXII_2016_17.html")  
  9.         webview.webViewClient = MyClient()  
  10.   
  11.         webview.setDownloadListener({ url, userAgent, contentDisposition, mimeType, contentLength ->  
  12.             val request = DownloadManager.Request(Uri.parse(url))  
  13.             request.setMimeType(mimeType)  
  14.             request.addRequestHeader("cookie", CookieManager.getInstance().getCookie(url))  
  15.             request.addRequestHeader("User-Agent", userAgent)  
  16.             request.setDescription("Downloading file...")  
  17.             request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType))  
  18.             request.allowScanningByMediaScanner()  
  19.             request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)  
  20.             request.setDestinationInExternalFilesDir(this@MainActivity, Environment.DIRECTORY_DOWNLOADS, ".png")  
  21.             val dm = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager  
  22.             dm.enqueue(request)  
  23.             Toast.makeText(applicationContext, "Downloading File", Toast.LENGTH_LONG).show()  
  24.         })  
  25.   
  26.     }  
  27.   
  28.     class MyClient : WebViewClient() {  
  29.         override fun shouldOverrideUrlLoading(view: WebView, Url: String): Boolean {  
  30.             view.loadUrl(Url)  
  31.             return true  
  32.   
  33.         }  
  34.     }  
  35.   
  36.     override fun onBackPressed() {  
  37.         if (webview.canGoBack())  
  38.             webview.goBack()  
  39.         else  
  40.             super.onBackPressed()  
  41.   
  42.     }  
  43. }   

Download Code

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


Similar Articles