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.
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.
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.
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));
}