42

I am using a code that check if user has internet active or not but after targeting sdk29 the functions bellow became deprecated

NetworkInfo

NetworkInfo.isConnected()

getActiveNetworkInfo()

Here is the code :

public static boolean isNetworkAvailable(Context context) {
    if(context == null) { return false; }
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    // if no network is available networkInfo will be null, otherwise check if we are connected
    try {
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
            Log.i("update_statut","Network is available : true");
            return true;
        }
    } catch (Exception e) {
        Log.i("update_statut",""+ e.getMessage());
    }
    Log.i("update_statut","Network is available : FALSE ");
    return false;
}
Community
  • 1
  • 1
Chaouki Anass
  • 937
  • 1
  • 10
  • 19
  • https://stackoverflow.com/questions/53532406/activenetworkinfo-type-is-deprecated-in-api-level-28/53532456#53532456 – AskNilesh Jul 30 '19 at 18:32

3 Answers3

84

It's deprecated base on Google Document

  • getActiveNetworkInfo is deprecated on API 29.
  • getAllNetworkInfo is deprecated on API 23.

So, If you want to find the Network Connection status, you can use this code.

kotlin :

private fun isNetworkAvailable(context: Context): Boolean {
    val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        val nw      = connectivityManager.activeNetwork ?: return false
        val actNw = connectivityManager.getNetworkCapabilities(nw) ?: return false
        return when {
            actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
            actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
            //for other device how are able to connect with Ethernet
            actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
            //for check internet over Bluetooth
            actNw.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) -> true
            else -> false
        }
    } else {
        val nwInfo = connectivityManager.activeNetworkInfo ?: return false
        return nwInfo.isConnected
    }
}

Java :

private Boolean isNetworkAvailable(Application application) {
    ConnectivityManager connectivityManager = (ConnectivityManager) application.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        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_CELLULAR) || actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) || actNw.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH));
    } else {
        NetworkInfo nwInfo = connectivityManager.getActiveNetworkInfo();
        return nwInfo != null && nwInfo.isConnected();
    }
}

you can see all NetworkCapability here.

Yoshimitsu
  • 4,343
  • 2
  • 22
  • 28
41

I have finally found a code that works on all APIs in case anybody want it

NetworkCapabilities is not deprecated in API 29 but it requires API 21 so I have called it on API 29 only.

However getActiveNetworkInfo() is deprecated only in API 29 and works on all APIs , so we can use it in all apis bellow 29

here's the code

    public static boolean isNetworkAvailable(Context context) {
    if(context == null)  return false;


    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivityManager != null) {


    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
            if (capabilities != null) {
                if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                    return true;
                } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                    return true;
                }  else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)){
                    return true;
                }
            }
        }

    else {

        try {
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
                Log.i("update_statut", "Network is available : true");
                return true;
            }
        } catch (Exception e) {
            Log.i("update_statut", "" + e.getMessage());
        }
    }
}
    Log.i("update_statut","Network is available : FALSE ");
    return false;
}
Chaouki Anass
  • 937
  • 1
  • 10
  • 19
  • There are some things wrong with this code. This code will break once Android R is released... Which is horrible. It also assumes the user can only connect to the internet with Cellular data or WiFi. What about an ethernet cable? I use that too. This code would break the app for me. – Zun Jul 31 '19 at 07:24
  • @Zun Why it will break on Android R ? PS : Please check my edit for ethernet cable – Chaouki Anass Jul 31 '19 at 17:40
  • `android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.Q` this means the new function will only be called in Android Q. Not Android Q or higher. Android R will call the old, outdated function cause the if-statement will fall into the else! – Zun Aug 01 '19 at 07:08
  • @Zun you are right . I have edited the code I guess its all ok now – Chaouki Anass Aug 01 '19 at 07:49
  • Isn't there a more general way, like the deprecated one? One that says "connected to the Internet in any possible way" ? Also, why doesn't the new way have `isConnectedOrConnecting()` ? What does it mean when you call `hasTransport` ? Is it this one, or that it's connected alone ? – android developer Feb 23 '21 at 08:49
3

You can find all the info in the official doc

This class was deprecated in API level 29.
Callers should instead use the ConnectivityManager.NetworkCallback API to learn about connectivity changes, or switch to use ConnectivityManager#getNetworkCapabilities or ConnectivityManager#getLinkProperties to get information synchronously. Keep in m`ind that while callbacks are guaranteed to be called for every event in order, synchronous calls have no such constraints, and as such it is unadvisable to use the synchronous methods inside the callbacks as they will often not offer a view of networking that is consistent (that is: they may return a past or a future state with respect to the event being processed by the callback). Instead, callers are advised to only use the arguments of the callbacks, possibly memorizing the specific bits of information they need to keep from one callback to another.

You can use something like:

if (connectivityManager != null) {
    if (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
       NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
       if (capabilities != null) {
           if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
               //...
           }
       }
   } else {
     // current code
   }
}
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841