Created
May 23, 2023 17:03
-
-
Save ExNDY/59596b2993dec4257771850ac1976f50 to your computer and use it in GitHub Desktop.
Network status monitoring - Android 25+, Jetpack Compose compatibility
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class NetworkMonitor( | |
applicationContext: Context, | |
) : NetworkConnectivityService { | |
private val connectivityManager = applicationContext.getSystemService( | |
Context.CONNECTIVITY_SERVICE | |
) as ConnectivityManager | |
override val networkStatus: Flow<NetworkStatus> = callbackFlow { | |
val connectivityCallback = object : NetworkCallback() { | |
override fun onAvailable(network: Network) { | |
val isAvailable: NetworkStatus = pingToGoogle() | |
trySend(isAvailable) | |
} | |
override fun onLosing(network: Network, maxMsToLive: Int) { | |
trySend(OFFLINE) | |
} | |
override fun onLost(network: Network) { | |
trySend(OFFLINE) | |
} | |
override fun onUnavailable() { | |
trySend(OFFLINE) | |
} | |
} | |
val request = NetworkRequest.Builder() | |
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) | |
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI) | |
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR) | |
.build() | |
connectivityManager.registerNetworkCallback(request, connectivityCallback) | |
awaitClose { | |
connectivityManager.unregisterNetworkCallback(connectivityCallback) | |
} | |
}.distinctUntilChanged().flowOn(Dispatchers.IO) | |
private fun pingToGoogle(): NetworkStatus { | |
return try { | |
Runtime.getRuntime().exec("ping -w -c 1 google.com").waitFor() | |
ONLINE | |
} catch (e: IOException) { | |
Timber.e("NetworkMonitor ping failed: $e") | |
OFFLINE | |
} catch (e: InterruptedException) { | |
Timber.e("NetworkMonitor ping failed: $e") | |
OFFLINE | |
} | |
} | |
} | |
interface NetworkConnectivityService { | |
val networkStatus: Flow<NetworkStatus> | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum class NetworkStatus { | |
UNKNOWN, | |
ONLINE, | |
OFFLINE | |
} | |
fun NetworkStatus.isOnline(): Boolean { | |
return this == ONLINE | |
} | |
fun NetworkStatus.isOffline(): Boolean { | |
return this != ONLINE | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment