// Android API 26+; Android System WebView 105+ // Dependencies: AndroidX AppCompat, Activity Result APIs and Core 1.5+. import android.content.Intent import android.net.Uri import android.net.ConnectivityManager import android.net.Network import android.os.Bundle import android.os.Message import android.view.ViewGroup import android.view.WindowManager import android.webkit.* import android.widget.FrameLayout import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat import org.json.JSONObject class KnocketActivity : AppCompatActivity() { private val chatUrl = "https://knocket.ai/mu/YOUR_IDENTIFIER" private lateinit var container: FrameLayout private var webView: WebView? = null private var fileCallback: ValueCallback>? = null private var loadErrorDialog: androidx.appcompat.app.AlertDialog? = null private lateinit var connectivity: ConnectivityManager private val networkCallback = object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) { runOnUiThread { if (lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) { webView?.evaluateJavascript("window.dispatchEvent(new Event('online'))", null) } } } } private val picker = registerForActivityResult( ActivityResultContracts.StartActivityForResult() ) { result -> val callback = fileCallback fileCallback = null val data = result.data val clips = data?.clipData val files = when { result.resultCode != RESULT_OK -> null clips != null -> Array(clips.itemCount) { index -> clips.getItemAt(index).uri } else -> WebChromeClient.FileChooserParams.parseResult(result.resultCode, data) } callback?.onReceiveValue(files) } private fun isChat(value: String): Boolean { val url = Uri.parse(value) val chat = Uri.parse(chatUrl) val actualPath = url.path ?: return false val expectedPath = chat.path ?: return false return url.scheme == chat.scheme && url.host == chat.host && url.port == chat.port && actualPath.trimEnd('/') == expectedPath.trimEnd('/') } private fun openExternal(value: String) { val uri = Uri.parse(value) if (uri.scheme !in listOf("https", "http", "mailto", "tel")) return runCatching { startActivity(Intent(Intent.ACTION_VIEW, uri)) }.onFailure { androidx.appcompat.app.AlertDialog.Builder(this) .setMessage("Unable to open link. Please try again.") .setPositiveButton("OK", null).show() } } private fun loadFailed() { if (isFinishing || isDestroyed || loadErrorDialog?.isShowing == true) return loadErrorDialog = androidx.appcompat.app.AlertDialog.Builder(this) .setMessage("Unable to load chat. Check your connection and try again.") .setPositiveButton("Retry") { _, _ -> webView?.loadUrl(chatUrl) } .setNegativeButton("Cancel", null).show() } private inner class Bridge { // Keep the bridge channel and host-control command names unchanged. @JavascriptInterface fun postMessage(value: String) { runOnUiThread { if (!isChat(webView?.url ?: "")) return@runOnUiThread val message = runCatching { JSONObject(value) }.getOrNull() ?: return@runOnUiThread when (message.optString("type")) { "closeWebView" -> finish() "openExternal" -> openExternal(message.optString("url")) } } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) WindowCompat.setDecorFitsSystemWindows(window, false) window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) container = FrameLayout(this) setContentView(container) ViewCompat.setOnApplyWindowInsetsListener(container) { view, insets -> val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) val ime = insets.getInsets(WindowInsetsCompat.Type.ime()) view.setPadding( bars.left, bars.top, bars.right, maxOf(bars.bottom, ime.bottom) ) insets } ViewCompat.requestApplyInsets(container) createWebView(savedInstanceState) connectivity = requireNotNull(getSystemService(ConnectivityManager::class.java)) connectivity.registerDefaultNetworkCallback(networkCallback) } private fun createWebView(savedInstanceState: Bundle? = null) { val current = WebView(this) webView = current container.addView(current, FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) with(current.settings) { javaScriptEnabled = true domStorageEnabled = true mediaPlaybackRequiresUserGesture = true allowFileAccess = false mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW setSupportMultipleWindows(true) } // Do not embed third-party iframes in this WebView. current.addJavascriptInterface(Bridge(), "closeWebView") current.webViewClient = object : WebViewClient() { override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) { if (request.isForMainFrame) loadFailed() } override fun onReceivedHttpError(view: WebView, request: WebResourceRequest, response: WebResourceResponse) { if (request.isForMainFrame) loadFailed() } override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean { val value = request.url.toString() if (!request.isForMainFrame) return true if (isChat(value)) return false openExternal(value) return true } override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean { if (webView === view) { webView = null fileCallback?.onReceiveValue(null) fileCallback = null container.removeView(view) view.destroy() container.post { if (!isFinishing && !isDestroyed) createWebView() } } else { (view.parent as? ViewGroup)?.removeView(view) view.destroy() } return true } } current.webChromeClient = object : WebChromeClient() { override fun onShowFileChooser(view: WebView, callback: ValueCallback>, params: FileChooserParams): Boolean { fileCallback?.onReceiveValue(null) fileCallback = callback return try { val intent = params.createIntent() intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, params.mode == FileChooserParams.MODE_OPEN_MULTIPLE) picker.launch(intent) true } catch (_: Exception) { callback.onReceiveValue(null); fileCallback = null; true } } override fun onCreateWindow(view: WebView, dialog: Boolean, gesture: Boolean, result: Message): Boolean { if (!gesture) return false val external = WebView(this@KnocketActivity) external.webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading(v: WebView, request: WebResourceRequest): Boolean { openExternal(request.url.toString()) v.destroy() return true } override fun onRenderProcessGone(v: WebView, detail: RenderProcessGoneDetail): Boolean { v.destroy() return true } } (result.obj as WebView.WebViewTransport).webView = external result.sendToTarget() return true } } current.setDownloadListener { url, _, _, _, _ -> openExternal(url) } if (savedInstanceState == null || current.restoreState(savedInstanceState) == null) { current.loadUrl(chatUrl) } } override fun onResume() { super.onResume() webView?.onResume() webView?.evaluateJavascript("window.dispatchEvent(new Event('online'))", null) } override fun onPause() { webView?.onPause(); super.onPause() } override fun onSaveInstanceState(out: Bundle) { webView?.saveState(out); super.onSaveInstanceState(out) } override fun onDestroy() { loadErrorDialog?.dismiss() fileCallback?.onReceiveValue(null) fileCallback = null connectivity.unregisterNetworkCallback(networkCallback) webView?.let { container.removeView(it) it.removeJavascriptInterface("closeWebView") it.destroy() } webView = null super.onDestroy() } } // AndroidManifest.xml: // // // // // // Open from an existing app screen, not as the app root. // startActivity(Intent(this, KnocketActivity::class.java)) // Keep adjustResize; do not add extra system-bar or keyboard padding.