Android getAllNetworkInfo() is Deprecated. What is the alternative?

后端 未结 6 1498
生来不讨喜
生来不讨喜 2021-01-31 09:33

I want to use the ConnectivityManager which provides the getAllNetworkInfo() method for checking the availability of network in Android. This method wa

相关标签:
6条回答
  • 2021-01-31 09:35

    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).

    0 讨论(0)
  • 2021-01-31 09:35

    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;
                }
            }
        }
    
    0 讨论(0)
  • 2021-01-31 09:36

    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;
                }
            }
    
    0 讨论(0)
  • 2021-01-31 09:37

    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

    0 讨论(0)
  • 2021-01-31 09:39

    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;  
        }  
    }  
    
    0 讨论(0)
  • 2021-01-31 09:46

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题