Check is Internet available - Should we check for NetworkCapabilities.TRANSPORT_BLUETOOTH, TRANSPORT_VPN, ... as well?

Viewed 169

Previously, before API 28, we can use NetworkInfo, to check whether Internet is available without much effort. A single call on isConnectedOrConnecting will be sufficient enough.

private static boolean isInternetAvailable(Context context) {
    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm == null) {
        // Will it happen ever?
        return false;
    }
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

But, quite a number of methods of NetworkInfo is deprecated. Hence, we need to modify our code to

private static boolean isInternetAvailable(Context context) {
    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm == null) {
        // Will it happen ever?
        return false;
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        Network activeNetwork = cm.getActiveNetwork();
        if (activeNetwork == null) {
            return false;
        }

        NetworkCapabilities networkCapabilities = cm.getNetworkCapabilities(activeNetwork);
        if (networkCapabilities != null) {
            if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                return true;
            } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                return true;
            } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)){
                return true;
            }
        }

        return false;
    } else {
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }
}

We was wondering, should we perform check on the following remaining capabilities, to determine whether Internet is available?

  • TRANSPORT_BLUETOOTH
  • TRANSPORT_VPN
  • TRANSPORT_WIFI_AWARE
  • TRANSPORT_LOWPAN

As, it is difficult to have access to all kinds of network connection, and we do not have luxury to do all the cases testing.

0 Answers
Related