30

I want to use the ConnectivityManager which provides the getAllNetworkInfo() method for checking the availability of network in Android. This method was deprecated in API level 23. And the developer documentation is suggesting to use getAllNetworks() instead. I tried but couldn't get the exact functionalities which I was getting out of my old code. Please someone could guide me how to use the getAllNetworks() method?

 public boolean isConnectingToInternet(){
    ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null) 
      {
          @SuppressWarnings("deprecation")
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
          //use getAllNetworks() instead
          if (info != null) 
              for (int i = 0; i < info.length; i++) 
                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                  {
                      return true;
                  }
      }
      return false;
}
JJD
  • 50,076
  • 60
  • 203
  • 339
Anees U
  • 1,077
  • 1
  • 12
  • 20
  • Possible duplicate of [ConnectivityManager getNetworkInfo(int) deprecated](http://stackoverflow.com/questions/32547006/connectivitymanager-getnetworkinfoint-deprecated) – Shirish Herwade Mar 31 '16 at 07:09
  • Answer here - http://stackoverflow.com/questions/32547006/connectivitymanager-getnetworkinfoint-deprecated – Shirish Herwade Mar 31 '16 at 07:10

6 Answers6

31

When i update my deprecated code and still want to support backward Api. i use this :

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.WANTED API VERSION){
//code
}else{
//code
}

In this way each device use the appropriate code for it. Example:

public class ConnectionDetector {

    private Context mContext;

    public ConnectionDetector(Context context) {
        this.mContext = context;
    }
    /**
     * Checking for all possible internet providers
     * **/
    public boolean isConnectingToInternet() {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Network[] networks = connectivityManager.getAllNetworks();
            NetworkInfo networkInfo;
            for (Network mNetwork : networks) {
                networkInfo = connectivityManager.getNetworkInfo(mNetwork);
                if (networkInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
                    return true;
                }
            }
        }else {
            if (connectivityManager != null) {
                //noinspection deprecation
                NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
                if (info != null) {
                    for (NetworkInfo anInfo : info) {
                        if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
                            LogUtils.d("Network",
                                    "NETWORKNAME: " + anInfo.getTypeName());
                            return true;
                        }
                    }
                }
            }
        }
        Toast.makeText(mContext,mContext.getString(R.string.please_connect_to_internet),Toast.LENGTH_SHORT).show();
        return false;
    }
}
Shridutt Kothari
  • 7,326
  • 3
  • 41
  • 61
Maor Hadad
  • 1,850
  • 21
  • 36
  • 1
    Please note that [NetworkInfo#getState](https://developer.android.com/reference/kotlin/android/net/NetworkInfo.html#getstate) is *deprecated*, too. – JJD Jul 24 '19 at 21:49
14

I've made utils that may help you to check:

  • If network is connected.
  • If WiFi is connected.
  • If mobile data is connected.

it uses old or new API depending on running platform :

import android.annotation.TargetApi;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.annotation.NonNull;

public class NetworkUtils {

    public static boolean isConnected(@NonNull Context context) {
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.isConnected());
    }

    public static boolean isWifiConnected(@NonNull Context context) {
        return isConnected(context, ConnectivityManager.TYPE_WIFI);
    }

    public static boolean isMobileConnected(@NonNull Context context) {
        return isConnected(context, ConnectivityManager.TYPE_MOBILE);
    }

    private static boolean isConnected(@NonNull Context context, int type) {
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            NetworkInfo networkInfo = connMgr.getNetworkInfo(type);
            return networkInfo != null && networkInfo.isConnected();
        } else {
            return isConnected(connMgr, type);
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private static boolean isConnected(@NonNull ConnectivityManager connMgr, int type) {
        Network[] networks = connMgr.getAllNetworks();
        NetworkInfo networkInfo;
        for (Network mNetwork : networks) {
            networkInfo = connMgr.getNetworkInfo(mNetwork);
            if (networkInfo != null && networkInfo.getType() == type && networkInfo.isConnected()) {
                return true;
            }
        }
        return false;
    }

}

Update:
More information about @TargetApi and @RequiresApi: https://stackoverflow.com/a/40008157/421467 https://developer.android.com/reference/kotlin/androidx/annotation/RequiresApi

JJD
  • 50,076
  • 60
  • 203
  • 339
Yakiv Mospan
  • 8,174
  • 3
  • 31
  • 35
  • Please have in mind that on some weird devices out there the: `connMgr.getNetworkInfo(mNetwork)` can throw a NullPointerExcecption. It happened to me today, seems that is thrown by the native method inside the **IConnectivityManager**. The workaround would be to try/catch this inside your _for_ loop and decide fallback on the deprecated method for this specific Network. – Marius Constantin Aug 25 '16 at 15:44
  • @MariusC thanks for reply, please send me stack trace of that crash to yakiv.mospan at gmail.com. It's very bad practice to wrap Nullpointer in try-catch. We need too avoid Nullpointer itself instead. Maybe something wrong is with `mNetwork`, maybe that weird device doesnt support some of networks that was returned by `getAllNetwokrs` ? – Yakiv Mospan Aug 29 '16 at 08:16
  • @MariusC btw, what device it was, was it working on other devices, are you sure you have permission `ACCESS_NETWORK_STATE` ? – Yakiv Mospan Aug 29 '16 at 08:23
  • Hi Yakiv, please find bellow the ticket I opened on Android Framework Project related with that bug: https://github.com/android/platform_frameworks_base/issues/123 – Marius Constantin Aug 30 '16 at 12:59
  • 1
    Also...I know it is a bad practice to catch that and it's an ugly workaround but so far this is the best thing I could do, there is no way you can avoid that because is happening randomly and you cannot any information on the Network instance to avoid that. – Marius Constantin Aug 30 '16 at 13:01
  • @YakivMospan The question indicates that [`NetworkInfo#isConnectedOrConnecting`](https://developer.android.com/reference/kotlin/android/net/NetworkInfo.html#isconnectedorconnecting) might be called which is *deprecated*, too. In that case your approach does not provide a workaround. – JJD Jul 24 '19 at 21:53
3

For someone needs Kotlin version, (Below is same code with Maor Hadad's)

fun Context.isNetworkConnected(): Boolean {
  val manager = getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    val allNetworks = manager?.allNetworks?.let { it } ?: return false
    allNetworks.forEach { network ->
      val info = manager.getNetworkInfo(network)
      if (info.state == NetworkInfo.State.CONNECTED) return true
    }
  } else {
    val allNetworkInfo = manager?.allNetworkInfo?.let { it } ?: return false
    allNetworkInfo.forEach { info ->
      if (info.state == NetworkInfo.State.CONNECTED) return true
    }
  }
  return false
}

This code is an extension method for Context.

Write down this code at any kotlin file(.kt), then you can use this method in any class which implements Context(such as Activity).

Mark
  • 493
  • 5
  • 10
  • Here is a more functional approach `return manager.allNetworks.any { NetworkInfo.State.CONNECTED == manager.getNetworkInfo(it).state }`. However, this does not resolve the issue since [NetworkInfo.html#getstate](https://developer.android.com/reference/kotlin/android/net/NetworkInfo.html#getstate) is *deprecated*, too. – JJD Jul 24 '19 at 22:00
2

Try following code:

ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);    
    Network[] networks = connectivityManager.getAllNetworks();
    NetworkInfo networkInfo;
    Network network;
        for (int i = 0; i < networks.length; i++){               
            network = networks[i];
            networkInfo = connectivityManager.getNetworkInfo(network);
            if ((networkInfo.getType() ==     ConnectivityManager.TYPE_WIFI) && (networkInfo.getState().equals(NetworkInfo.State.CONNECTED))) {
               ConnectivityManager.setProcessDefaultNetwork(network);
                break;
            }
        }
Akshay
  • 6,029
  • 7
  • 40
  • 59
2

Try this

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
Network[] networks = cm.getAllNetworks();
if (cm != null) {
    for (Network netinfo : networks) {
        NetworkInfo ni = cm.getNetworkInfo(netinfo);
        if (ni.isConnected() && ni.isAvailable()) {
                connected = true;
            }
        }
    }
JJD
  • 50,076
  • 60
  • 203
  • 339
-2

Try this one .It is the simplest way.

public static boolean isNetworkAvailable(Activity activity) {  
        ConnectivityManager connectivity = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);  
        if (connectivity == null) {  
            return false;  
        } else {  
            NetworkInfo[] info = connectivity.getAllNetworkInfo();  
            if (info != null) {  
                for (int i = 0; i < info.length; i++) {  
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {  
                        return true;  
                    }  
                }  
            }  
        }  
        return false;  
    }  
}  
Shridutt Kothari
  • 7,326
  • 3
  • 41
  • 61
dev garg
  • 194
  • 1
  • 1
  • 12
  • Once again, the question asks what the alternative is to `NetworkInfo` .... apparently no one (here anyway) reads the question and/or can provide an answer. Frustrating when one is looking for an answer. – Prescott Chartier Mar 09 '20 at 21:28