File Downloads
Update WebViewActivity with .ics File Download Support
.ics File Download Supportimport android.Manifest
import android.app.DownloadManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.webkit.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import java.io.File
class WebViewActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_webview)
val webView: WebView = findViewById(R.id.webView)
webView.webViewClient = WebViewClient()
webView.webChromeClient = WebChromeClient()
// Enable JavaScript
val webSettings: WebSettings = webView.settings
webSettings.javaScriptEnabled = true
// Allow Media Playback Inline
webSettings.mediaPlaybackRequiresUserGesture = false
// Enable file downloads
enableFileDownloads(webView)
// Load the web app URL
webView.loadUrl("https://{clientId}.loveslisa.tech/s/{showId}")
// Handle communication from the web app
webView.addJavascriptInterface(object : Any() {
@JavascriptInterface
fun postMessage(message: String) {
// Process the message from the web app
println("Message from LiSA: $message")
}
}, "MessageFromLiSA")
}
private fun enableFileDownloads(webView: WebView) {
// Request permissions for downloading files
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
1
)
}
// Set up a Download Listener
webView.setDownloadListener { url, userAgent, contentDisposition, mimeType, _ ->
if (mimeType == "text/calendar" || url.endsWith(".ics")) {
// Use DownloadManager to download the file
val request = DownloadManager.Request(Uri.parse(url))
request.setMimeType(mimeType)
request.addRequestHeader("User-Agent", userAgent)
request.setDescription("Downloading calendar event...")
request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType))
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS,
URLUtil.guessFileName(url, contentDisposition, mimeType)
)
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
val downloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
downloadManager.enqueue(request)
// Inform the user
println("Downloading .ics file from: $url")
}
}
}
}Key Changes and Additions
Steps to Integrate
Add the WebViewActivity to Your Android App:
Request Permissions in AndroidManifest.xml
AndroidManifest.xmlAdd the WebView to Your Layout
Handle File Downloads
Permissions Handling
Last updated