How to check if WiFi connection has internet on Android

Viewed 308

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.

2 Answers

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