nowinandroid icon indicating copy to clipboard operation
nowinandroid copied to clipboard

[Bug]: NetworkMonitor not sending callback when a network loses connection

Open AntsyLich opened this issue 2 years ago • 3 comments

Is there an existing issue for this?

  • [X] I have searched the existing issues

Is there a StackOverflow question about this issue?

  • [X] I have searched StackOverflow

What happened?

Scenario 1: I connected to a WiFi/enabled mobile data with no internet connection. I expected to see the "You aren't connected to the internet" snackbar but it didn't appear. (I did find answer about this in StackOverflow that we should use NetworkCapabilities.NET_CAPABILITY_VALIDATED)

Scenario 2: I connected to a wifi with internet connection and disabled the internet from the router. My device reports that the wifi has no connection but the app doesn't show the "You aren't connected to the internet" snackbar. I tried to use NetworkCapabilities.NET_CAPABILITY_VALIDATED but the result was same.

Relevant logcat output

No response

Code of Conduct

  • [X] I agree to follow this project's Code of Conduct

AntsyLich avatar Aug 18 '23 05:08 AntsyLich

The NET_CAPABILITY_INTERNET capability means that the network is configured to reach the general Internet. It may or may not actually provide connectivity ; the NET_CAPABILITY_VALIDATED bit indicates that the system found actual connectivity to the general Internet the last time it checked. Apps interested in actual connectivity should usually look at both these capabilities.
https://developer.android.com/reference/android/net/NetworkCapabilities

NET_CAPABILITY_VALIDATED has been added in API 23, but our current min is 21. We could fallback to NET_CAPABILITY_INTERNET only in this case.

val request = Builder()
    .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
    .apply { if (SDK_INT >= M) addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) }
    .build()

SimonMarquis avatar Aug 19 '23 09:08 SimonMarquis

Yeah that makes sense. I was actually using the implementation on an another app whose min api is 26.

And can you give any insight for scenario 2?

AntsyLich avatar Aug 19 '23 09:08 AntsyLich

Are you sure you only have a single network connection? You can try debugging this by printing to logcat the Network properties.

Also, this network monitor is not bulletproof. For instance, if you use a public hotspot that requires some sort of login to access the internet, this might still be detected as NET_CAPABILITY_VALIDATED if the framework uses a simple heuristic like a ping to Google's servers (although I don't know if this is what's really used to detect that).

SimonMarquis avatar Aug 19 '23 12:08 SimonMarquis