class WifiConnectionMonitor(app: Application) { @VisibleForTesting internal val callbacks = mutableListOf<(Boolean) -> Unit>() @VisibleForTesting internal var connectivityManager = app.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager @VisibleForTesting internal var lastKnownStateWasAvailable: Boolean? = null @VisibleForTesting internal var isRegistered = false @Synchronized set @VisibleForTesting internal val frameworkListener = object : ConnectivityManager.NetworkCallback() { override fun onLost(network: Network) { notifyListeners(false) lastKnownStateWasAvailable = false } override fun onAvailable(network: Network) { notifyListeners(true) lastKnownStateWasAvailable = true } } internal fun notifyListeners(value: Boolean) { val items = ArrayList(callbacks) items.forEach { it(value) } }
Attaches itself to the [Application] and listens for WIFI available/not available events. This allows the calling code to set simpler listeners.