0

I am using this code to check internet availability

public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null) {
        NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
        if (info != null) {
            for (NetworkInfo anInfo : info) {
                if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
    }
    return false;
}

But this method is now deprecated

.getState()

I am targeting Sdk Version 28 . Is there any alternative method I can use ?

Chaouki Anass
  • 937
  • 1
  • 10
  • 19

1 Answers1

0
private static boolean isConnected(Context context) {
        NetworkInfo info = null;
        try {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            info = cm.getActiveNetworkInfo();
        } catch (Exception e) {
        }
        return (info != null && info.isConnected() && info.getType() == NetworkCapabilities.TRANSPORT_CELLULAR);
    }

You can use NetworkCapabilities.TRANSPORT_WIFI and NetworkCapabilities.TRANSPORT_CELLULARto distinguish between cellular and wifi connection.

Sahil
  • 86
  • 2
  • 6