Showing posts with label webview. Show all posts

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

How To Add Download Listener To WebView In Kotlin How To Add Download Listener To WebView In Kotlin

A blog about android developement

webview

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.