5

I am trying to find a way to check if my current WiFi connection has internet.

Using the usual option of ping or trying to reach a site won't work if I also have mobile data open because it will return true due to that.

theblitz
  • 6,683
  • 16
  • 60
  • 114

2 Answers2

0

Check hasTransport (from NetworkCapabilities)

You can use the value TRANSPORT_WIFI to test WIFI connection

connection.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) 

I also found some gists, hope they can help you

Check Internet Connection [API21+][API29+ supported] Lifecycle aware

Class to check the Connectivity and Internet Access of an Android device.

Stefano Sansone
  • 2,377
  • 7
  • 20
  • 39
0

This is the code that worked for me. Note: if cellular data is valid in your application then you can add it to the last line.

    private static boolean isNetworkAvailable(@NonNull Context context) {

    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    Network nw = connectivityManager.getActiveNetwork();
    if (nw == null) return false;
    NetworkCapabilities actNw = connectivityManager.getNetworkCapabilities(nw);
    return actNw != null && (actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
            actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET));
}
Linden
  • 38
  • 1
  • 6