CCCPaste

networkchecker

class NetworkChecker(private val context: Context) { // provided by Koin

    private val connectivityManager by lazy {
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    }

    // Quick check for potential connectivity
    fun isNetworkConnected(): Boolean {
        val network = connectivityManager.activeNetwork ?: return false
        val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return false

        return when {
            capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
            capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
            capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
            else -> false
        }
    }

    // Actual internet connectivity check
    suspend fun hasInternetAccess(timeout: Long = 3000L): Boolean {
        return withContext(Dispatchers.IO) {

        if (!isNetworkConnected()) return@withContext false

            try {
                withTimeout(timeout) {
                    val url = URL("http://example.com")
                    val urlConnection = url.openConnection() as HttpURLConnection
                    urlConnection.setRequestProperty("Connection", "close")
                    urlConnection.connectTimeout = timeout.toInt()
                    urlConnection.connect()
                    urlConnection.responseCode == 200 || urlConnection.responseCode == 204
                }
            } catch (e: Exception) {
                Timber.e("hasInternetAccess exception: $e")
                false
            }
        }
    }

}