0

The code i am using to check internet connectivity so far is

private boolean isOnline() {
        boolean haveConnectedWifi = false;
        boolean haveConnectedMobile = false;

        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    haveConnectedWifi = true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    haveConnectedMobile = true;
        }
        return haveConnectedWifi || haveConnectedMobile;
    }

my code is working fine till android 5.0 but in android 6.0 the app crashes can anyone help me regarding this issue and provide me a better code that can test internet connectivity Thanks Regards

bufferking
  • 47
  • 1
  • 9

2 Answers2

1

getAllNetworkInfo is deprecated

you need to use: getActiveNetworkInfo()

code:

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null) { // connected to the internet
        if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
            // connected to wifi
            Toast.makeText(context, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
        } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
            //connected to Data
            Toast.makeText(context, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
        }
    } else {
        // not connected to the internet
    }
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62
0

From the ConnectivityManager documentation:

NetworkInfo[] getAllNetworkInfo ()

This method was deprecated in API level 23.

This method does not support multiple connected networks of the same type. Use getAllNetworks() and getNetworkInfo(android.net.Network) instead.

Bear in mind getAllNetworks() was introduced in API Level 21, so you may need to run two separate approaches based on the user's OS version.

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
    // Use getAllNetworks()
} else{
    // Use getAllNetworkInfo()
}
Community
  • 1
  • 1
Michael Dodd
  • 10,102
  • 12
  • 51
  • 64