diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 0c3540e..c36dc80 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -23,6 +23,7 @@ the abbreviated format. --> + (R.id.retryButton).setOnClickListener { if (isOnline()) launchTwa() } + } + } + + // the web app's service worker, which serves its offline page, only exists after one online launch + override fun shouldLaunchImmediately(): Boolean = false + + // set once the browser finished loading a page, as a launch that gets interrupted earlier has not registered the service worker yet + override fun getCustomTabsCallback(): CustomTabsCallback { + val preferences = applicationContext.getSharedPreferences(PREFERENCES_NAME, MODE_PRIVATE) + + return object : QualityEnforcer() { + override fun onNavigationEvent(navigationEvent: Int, extras: Bundle?) { + super.onNavigationEvent(navigationEvent, extras) + if (navigationEvent == NAVIGATION_FINISHED) preferences.edit { putBoolean(KEY_LOADED_BEFORE, true) } + } + } + } + + override fun onDestroy() { + if (offlineHint?.get() === this) offlineHint = null + super.onDestroy() + } + + private fun hasLoadedBefore() = + getSharedPreferences(PREFERENCES_NAME, MODE_PRIVATE).getBoolean(KEY_LOADED_BEFORE, false) + + // an always-on VPN such as Tailscale is the active network and reports internet even with nothing underneath it, so only non-VPN networks count + @Suppress("DEPRECATION") // `allNetworks` has no synchronous replacement + private fun isOnline(): Boolean { + val manager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + return manager.allNetworks.any { network -> + manager.getNetworkCapabilities(network)?.run { + hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && + hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) + } == true + } } override fun createTwaLauncher(): TwaLauncher { @@ -40,4 +96,11 @@ class LauncherActivity : com.google.androidbrowserhelper.trusted.LauncherActivit // mirrors the web app's `protocol_handlers`, which Chrome does not apply to a TWA override fun getProtocolHandlers(): Map = mapOf("web+vibetype" to "https://${getString(R.string.hostName)}/open?url=%s".toUri()) + + private companion object { + const val KEY_LOADED_BEFORE = "loadedBefore" + const val PREFERENCES_NAME = "si.maev.twa.launch" + + var offlineHint: WeakReference? = null + } } diff --git a/app/src/main/res/drawable/offline_retry_button.xml b/app/src/main/res/drawable/offline_retry_button.xml new file mode 100644 index 0000000..30d2a9a --- /dev/null +++ b/app/src/main/res/drawable/offline_retry_button.xml @@ -0,0 +1,11 @@ + + + + + + + + + + diff --git a/app/src/main/res/layout/activity_offline.xml b/app/src/main/res/layout/activity_offline.xml new file mode 100644 index 0000000..33c7333 --- /dev/null +++ b/app/src/main/res/layout/activity_offline.xml @@ -0,0 +1,34 @@ + + + + + + +