android / nowinandroid

A fully functional Android app built entirely with Kotlin and Jetpack Compose
Apache License 2.0
16.98k stars 3.1k forks source link

Missing implementation of NET_CAPABILITY_VALIDATED in ConnectivityManager #1290

Open loke101 opened 8 months ago

loke101 commented 8 months ago

The current implementation of ConnectivityManager.isCurrentlyConnected() does not check for the NET_CAPABILITY_VALIDATED capability, leading to incorrect behavior when determining network connectivity status.

Steps to Reproduce:

private fun ConnectivityManager.isCurrentlyConnected() = when { Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> { activeNetwork ?.let { network -> getNetworkCapabilities(network)?.let { capabilities -> capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) } } ?: false } else -> activeNetworkInfo?.isConnected ?: false }

val networkCapabilities = connectivityManager.getNetworkCapabilities(network) val hasInternetCapability = networkCapabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) if (hasInternetCapability == true) { networks += network channel.trySend(true) }

yongsuk44 commented 8 months ago

In Android OS, differentiating between NET_CAPABILITY_INTERNET and NET_CAPABILITY_VALIDATED is designed to give developers more granular control over network connections. : link

It appears that the differentiation between each status value, as currently implemented, is intended for usage according to their respective purposes.

If you have a different opinion or further insights, please feel free to leave a comment!

loke101 commented 8 months ago

Then how can we check if we are connected to WIFI but has internet connection or not ?? @yongsuk44

yongsuk44 commented 8 months ago

@loke101 If you're asking about how to check if Wi-Fi is connected but not actually connected to the internet, I think I would handle it like this:

NetworkRequest.Builder()
    .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
    .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
    .build()

// ...

val networkCapabilities = getNetworkCapabilities(activeNetwork)

val hasActiveInternetConnection =
    networkCapabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
        && networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)

By doing this, you should be able to determine cases where Wi-Fi is connected but there is no internet connection.

Link