NetworkMonitor
This commit is contained in:
@@ -13,6 +13,8 @@ import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.launch
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
@@ -33,13 +35,16 @@ class NetworkMonitor @Inject constructor(
|
||||
override fun onAvailable(network: Network) {
|
||||
performPingCheck()
|
||||
}
|
||||
|
||||
override fun onLost(network: Network) {
|
||||
_isConnected.postValue(false)
|
||||
}
|
||||
}
|
||||
|
||||
fun startMonitoring() {
|
||||
val network = connectivityManager.activeNetwork
|
||||
if (network != null) {
|
||||
performPingCheck()
|
||||
}
|
||||
val networkRequest = NetworkRequest.Builder()
|
||||
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||
.build()
|
||||
@@ -58,10 +63,13 @@ class NetworkMonitor @Inject constructor(
|
||||
private fun performPingCheck() {
|
||||
networkScope.launch {
|
||||
try {
|
||||
// Ping Google's public DNS server
|
||||
val process = Runtime.getRuntime().exec("/system/bin/ping -c 1 8.8.8.8")
|
||||
val isReachable = process.waitFor() == 0
|
||||
val url = URL("https://www.google.com")
|
||||
val connection = url.openConnection() as HttpURLConnection
|
||||
connection.connectTimeout = 2000
|
||||
connection.connect()
|
||||
val isReachable = connection.responseCode == 200
|
||||
_isConnected.postValue(isReachable)
|
||||
connection.disconnect()
|
||||
} catch (e: Exception) {
|
||||
_isConnected.postValue(false)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user