From 9169e3a37943ab186a65354ae0f8781962071f24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erik=20Bj=C3=A4reholt?= Date: Fri, 5 Jan 2024 17:28:42 +0100 Subject: [PATCH] fix: attempt at fixing CSV exports crashing app --- .../android/fragments/WebUIFragment.kt | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/mobile/src/main/java/net/activitywatch/android/fragments/WebUIFragment.kt b/mobile/src/main/java/net/activitywatch/android/fragments/WebUIFragment.kt index cf77b5e..a5f522a 100644 --- a/mobile/src/main/java/net/activitywatch/android/fragments/WebUIFragment.kt +++ b/mobile/src/main/java/net/activitywatch/android/fragments/WebUIFragment.kt @@ -97,6 +97,7 @@ class WebUIFragment : Fragment() { myWebView.settings.javaScriptEnabled = true myWebView.settings.domStorageEnabled = true + myWebView.addJavascriptInterface(WebAppInterface(context), "Android") arguments?.let { it.getString(ARG_URL)?.let { it1 -> myWebView.loadUrl(it1) } } @@ -145,3 +146,24 @@ class WebUIFragment : Fragment() { } } } + +class WebAppInterface(private val mContext: Context) { + @JavascriptInterface + fun downloadCSV(csv: String, filename: String) { + downloadFile(csv, filename, "text/csv") + } + + @JavascriptInterface + fun downloadJSON(csv: String, filename: String) { + downloadFile(csv, filename, "application/json") + } + + fun downloadFile(csv: String, filename: String, mimetype: String) { + val file = File(mContext.getExternalFilesDir(null), filename) + file.writeText(csv) + val intent = Intent(Intent.ACTION_VIEW) + intent.setDataAndType(Uri.fromFile(file), mimetype) + intent.flags = Intent.FLAG_ACTIVITY_NO_HISTORY + mContext.startActivity(intent) + } +}