Lifecycle independent continuous internet connection listener in Android

16 Views Asked by At

Checking internet connectivity in Android apps is a very common use-case. I've already read many answers posted on the internet connectivity but they are not exactly what I'm looking for.

I am currently using ConnectivityManager to check if the internet is available or not. I have made an extension fun for this:

fun Context.isOnline(): Boolean {
        val connectivityManager =
            getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val capabilities: NetworkCapabilities? = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
        if (capabilities != null) {
            if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                Timber.tag("Internet").i("NetworkCapabilities.TRANSPORT_CELLULAR")
                return true
            } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                Timber.tag("Internet").i("NetworkCapabilities.TRANSPORT_WIFI")
                return true
            } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
                Timber.tag("Internet").i("NetworkCapabilities.TRANSPORT_ETHERNET")
                return true
            }
        }
        return false
    }

The problem with this method is it will check if the internet connection is active only once when the Activity or Fragment has been initialized.

I want to continuously check the internet connection in my app regardless of the Activity or Fragment lifecycle. Any help will be appreciated!

0

There are 0 best solutions below