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 support.
- Setting up the project with Library.
- Implementing the Download Listener with Kotlin.
Step 1 - Creating a new project with Kotlin
- Open Android Studio and select "Create new project".
- Name the project as per your wish and tick the "Kotlin checkbox support".
- Then, select your Activity type (For Example - Navigation Drawer Activity, Empty Activity, etc.).
- 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
- We need to add our WebView to our activity_main.xml file and initialize the WebView control.
- Then, add the following lines.
Here, we have to add the download manager request with media scanner to notify that the file is downloading.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() })
- 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.
Follow Us
Were this world an endless plain, and by sailing eastward we could for ever reach new distances