ConnectivityManager getNetworkInfo(int) deprecated

kyleED picture kyleED · Sep 13, 2015 · Viewed 102.9k times · Source

Using compileSdkVersion 23, however trying to support as far back as 9.

getNetworkInfo(int) was deprecated in 23. The suggestion was to use getAllNetworks() and getNetworkInfo(Network) instead. However both of these require minimum of API 21.

Is there a class that we can use in the support package that can assist with this?

I know that a solution was proposed before, however the challenge of my minimum API requirements of 9 poses a problem.

Answer

Cheese Bread picture Cheese Bread · Sep 24, 2015

You can use:

getActiveNetworkInfo();

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
    } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
        // connected to mobile data
    }
} else {
    // not connected to the internet
}

Or in a switch case

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) { 
    // connected to the internet
    switch (activeNetwork.getType()) {
        case ConnectivityManager.TYPE_WIFI:
            // connected to wifi
            break;
        case ConnectivityManager.TYPE_MOBILE:
            // connected to mobile data
            break;
        default:
            break;
    }
} else {
    // not connected to the internet
}