updated NetworkChecker.kt
This commit is contained in:
@@ -37,20 +37,37 @@ class NetworkMonitor @Inject constructor(
|
||||
override fun onAvailable(network: Network) {
|
||||
performPingCheck()
|
||||
}
|
||||
|
||||
override fun onLost(network: Network) {
|
||||
_isConnected.postValue(false)
|
||||
}
|
||||
|
||||
override fun onCapabilitiesChanged(
|
||||
network: Network,
|
||||
networkCapabilities: NetworkCapabilities
|
||||
) {
|
||||
// Recheck connectivity when capabilities change (e.g., network becomes validated)
|
||||
performPingCheck()
|
||||
}
|
||||
}
|
||||
|
||||
fun startMonitoring() {
|
||||
val network = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
connectivityManager.activeNetwork
|
||||
// Check initial connectivity status
|
||||
val isInitiallyConnected = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
val network = connectivityManager.activeNetwork
|
||||
val capabilities = connectivityManager.getNetworkCapabilities(network)
|
||||
capabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) == true
|
||||
} else {
|
||||
val activeNetworkInfo = connectivityManager.activeNetworkInfo
|
||||
activeNetworkInfo?.isConnected == true
|
||||
}
|
||||
|
||||
}
|
||||
if (network != null) {
|
||||
if (isInitiallyConnected) {
|
||||
performPingCheck()
|
||||
} else {
|
||||
_isConnected.postValue(false)
|
||||
}
|
||||
|
||||
val networkRequest = NetworkRequest.Builder()
|
||||
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||
.build()
|
||||
@@ -62,18 +79,23 @@ class NetworkMonitor @Inject constructor(
|
||||
try {
|
||||
connectivityManager.unregisterNetworkCallback(networkCallback)
|
||||
} catch (_: IllegalArgumentException) {
|
||||
// Ignore if callback was not registered
|
||||
}
|
||||
networkScope.cancel()
|
||||
}
|
||||
|
||||
private fun performPingCheck(){
|
||||
private fun performPingCheck() {
|
||||
networkScope.launch {
|
||||
try {
|
||||
val url = URL("https://www.google.com")
|
||||
val connection = url.openConnection() as HttpURLConnection
|
||||
connection.connectTimeout = 2000
|
||||
connection.readTimeout = 2000
|
||||
connection.setRequestProperty("Connection", "close")
|
||||
connection.connect()
|
||||
val isReachable = connection.responseCode == 200
|
||||
|
||||
// Consider any 2xx response as successful
|
||||
val isReachable = connection.responseCode in 200..299
|
||||
_isConnected.postValue(isReachable)
|
||||
connection.disconnect()
|
||||
} catch (e: Exception) {
|
||||
@@ -81,4 +103,4 @@ class NetworkMonitor @Inject constructor(
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user