Android getAllNetworkInfo() is Deprecated. What is

2019-03-09 09:14发布

I want to use the Connectivity manager which provide the method getAllNetworkInfo() for checking the availability of network in Android. This method was deprecated in API level 23. And Developer doc is suggesting to use getAllNetworks() instead. I tried but counldn't get the exact functionalities I was getting out of my old code. Please someone could guide me how to use getAllNetworks() method. Below is the code which I'm using:

 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;
}

6条回答
冷血范
2楼-- · 2019-03-09 09:14

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;  
    }  
}  
查看更多
老娘就宠你
3楼-- · 2019-03-09 09:16

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

查看更多
手持菜刀,她持情操
4楼-- · 2019-03-09 09:22

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

查看更多
神经病院院长
5楼-- · 2019-03-09 09:25

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;
            }
        }
查看更多
一夜七次
6楼-- · 2019-03-09 09:38

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;
    }
}
查看更多
We Are One
7楼-- · 2019-03-09 09:38

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;
                }
            }
        }
查看更多
登录 后发表回答