neleon

networkchecker

Oct 23rd, 2025
1,319
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.65 KB | Source Code | 0 0
  1. class NetworkChecker(private val context: Context) { // provided by Koin
  2.  
  3.     private val connectivityManager by lazy {
  4.         context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
  5.     }
  6.  
  7.     // Quick check for potential connectivity
  8.     fun isNetworkConnected(): Boolean {
  9.         val network = connectivityManager.activeNetwork ?: return false
  10.         val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return false
  11.  
  12.         return when {
  13.             capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
  14.             capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
  15.             capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
  16.             else -> false
  17.         }
  18.     }
  19.  
  20.     // Actual internet connectivity check
  21.     suspend fun hasInternetAccess(timeout: Long = 3000L): Boolean {
  22.         return withContext(Dispatchers.IO) {
  23.  
  24.         if (!isNetworkConnected()) return@withContext false
  25.  
  26.             try {
  27.                 withTimeout(timeout) {
  28.                     val url = URL("http://example.com")
  29.                     val urlConnection = url.openConnection() as HttpURLConnection
  30.                     urlConnection.setRequestProperty("Connection", "close")
  31.                     urlConnection.connectTimeout = timeout.toInt()
  32.                     urlConnection.connect()
  33.                     urlConnection.responseCode == 200 || urlConnection.responseCode == 204
  34.                 }
  35.             } catch (e: Exception) {
  36.                 Timber.e("hasInternetAccess exception: $e")
  37.                 false
  38.             }
  39.         }
  40.     }
  41.  
  42. }
Advertisement
Add Comment
Please, Sign In to add comment