下面列出了android.net.ConnectivityManager#getAllNetworks ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static int getNetWorkState() {
if (mContext == null) {
throw new UnsupportedOperationException("please use NetUtils before init it");
}
// 得到连接管理器对象
ConnectivityManager connMgr = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
//获取所有网络连接的信息
Network[] networks = connMgr.getAllNetworks();
//通过循环将网络信息逐个取出来
for (int i = 0; i < networks.length; i++) {
//获取ConnectivityManager对象对应的NetworkInfo对象
NetworkInfo networkInfo = connMgr.getNetworkInfo(networks[i]);
if (networkInfo.isConnected()) {
if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
return NETWORK_MOBILE;
} else {
return NETWORK_WIFI;
}
}
}
return NETWORK_NONE;
}
private static String[] readDnsServersFromConnectionManager(Context context) {
LinkedList<String> dnsServers = new LinkedList<>();
if (Build.VERSION.SDK_INT >= 21 && context != null) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
for (Network network : connectivityManager.getAllNetworks()) {
NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
if (networkInfo.getType() == activeNetworkInfo.getType()) {
LinkProperties lp = connectivityManager.getLinkProperties(network);
for (InetAddress addr : lp.getDnsServers()) {
dnsServers.add(addr.getHostAddress());
}
}
}
}
}
return dnsServers.isEmpty() ? new String[0] : dnsServers.toArray(new String[dnsServers.size()]);
}
static boolean vpnActive(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null)
return false;
try {
for (Network network : cm.getAllNetworks()) {
NetworkCapabilities caps = cm.getNetworkCapabilities(network);
if (caps != null && caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN))
return true;
}
} catch (Throwable ex) {
Log.w(ex);
}
return false;
}
public static String ipAddress(final Context context) {
final ConnectivityManager manager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
if (manager != null) {
final Network[] networks = manager.getAllNetworks();
if (networks != null) {
for (final Network network : networks) {
final NetworkInfo info = manager.getNetworkInfo(network);
if (info.isConnected()) {
if (info.getType() == ConnectivityManager.TYPE_WIFI) {
return getIpAddressFromWifi(context);
} else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
return getIpAddressFromMobile();
}
}
}
}
}
return null;
}
public static boolean isWifiConnected(Context context) {
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return mWifi.isConnected();
} else {
Network[] nets = connManager.getAllNetworks();
for(Network net : nets) {
NetworkInfo ni = connManager.getNetworkInfo(net);
if (ni.getType() == ConnectivityManager.TYPE_WIFI
|| ni.getType() == ConnectivityManager.TYPE_ETHERNET
&& ni.isConnected()) return true;
}
}
return false;
}
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null)
return false;
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.isConnected())
return true;
Network[] networks = cm.getAllNetworks();
if (networks == null)
return false;
for (Network network : networks) {
ni = cm.getNetworkInfo(network);
if (ni != null && ni.getType() != ConnectivityManager.TYPE_VPN && ni.isConnected())
return true;
}
return false;
}
public LegacyVpnRunner(VpnConfig config, String[] racoon, String[] mtpd) {
super(TAG);
mConfig = config;
mDaemons = new String[] {"racoon", "mtpd"};
// TODO: clear arguments from memory once launched
mArguments = new String[][] {racoon, mtpd};
mSockets = new LocalSocket[mDaemons.length];
// This is the interface which VPN is running on,
// mConfig.interfaze will change to point to OUR
// internal interface soon. TODO - add inner/outer to mconfig
// TODO - we have a race - if the outer iface goes away/disconnects before we hit this
// we will leave the VPN up. We should check that it's still there/connected after
// registering
mOuterInterface = mConfig.interfaze;
if (!TextUtils.isEmpty(mOuterInterface)) {
final ConnectivityManager cm = ConnectivityManager.from(mContext);
for (Network network : cm.getAllNetworks()) {
final LinkProperties lp = cm.getLinkProperties(network);
if (lp != null && lp.getAllInterfaceNames().contains(mOuterInterface)) {
final NetworkInfo networkInfo = cm.getNetworkInfo(network);
if (networkInfo != null) mOuterConnection.set(networkInfo.getType());
}
}
}
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
mContext.registerReceiver(mBroadcastReceiver, filter);
}
private static String getDnsServer(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null)
return DEFAULT_DNS;
LinkProperties props = null;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
for (Network network : cm.getAllNetworks()) {
NetworkInfo ni = cm.getNetworkInfo(network);
if (ni != null && ni.isConnected()) {
props = cm.getLinkProperties(network);
Log.i("Old props=" + props);
break;
}
}
else {
Network active = cm.getActiveNetwork();
if (active == null)
return DEFAULT_DNS;
props = cm.getLinkProperties(active);
Log.i("New props=" + props);
}
if (props == null)
return DEFAULT_DNS;
List<InetAddress> dns = props.getDnsServers();
if (dns.size() == 0)
return DEFAULT_DNS;
else
return dns.get(0).getHostAddress();
}
public static boolean isConnectedToWifi(Context context) {
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connMgr != null) {
for (Network network : connMgr.getAllNetworks()) {
NetworkInfo networkInfo = connMgr.getNetworkInfo(network);
if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return networkInfo.isConnected();
}
}
}
return false;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static Network[] getConnectedNetworks(ConnectivityManager conMan, int type) {
ArrayList<Network> nwList = new ArrayList<Network>();
Network[] nw = conMan.getAllNetworks();
for (int i = 0; i < nw.length;i++) {
NetworkInfo ni = conMan.getNetworkInfo(nw[i]);
if (ni != null && (ni.getType() == type || type == -1) && ni.isConnected())
nwList.add(nw[i]);
}
return nwList.toArray(new Network[nwList.size()]);
}
/**
* 网络是否可用
*/
public static boolean isNetworkAvailable(Context context) {
try {
ConnectivityManager mgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (mgr == null) {
return false;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Network[] networks = mgr.getAllNetworks();
NetworkInfo networkInfo;
for (Network mNetwork : networks) {
networkInfo = mgr.getNetworkInfo(mNetwork);
if (networkInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
return true;
}
}
} else {
NetworkInfo[] info = mgr.getAllNetworkInfo();
if (info != null) {
for (NetworkInfo anInfo : info) {
if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
} catch (Exception e) {
return true;
}
return false;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private LinkProperties getLinkProperties(ConnectivityManager connectivityManager, int cap) {
Network nets[] = connectivityManager.getAllNetworks();
for (Network n: nets) {
LinkProperties linkProperties = connectivityManager.getLinkProperties(n);
NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(n);
String interfaceName = linkProperties.getInterfaceName();
if (interfaceName != null && networkCapabilities != null) {
if (networkCapabilities.hasTransport(cap))
return linkProperties;
}
}
return null;
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private static boolean isInternetAvailable(ConnectivityManager connectivityManager) {
Network[] allNetworks = connectivityManager.getAllNetworks();
if (allNetworks != null) {
for (Network network : allNetworks) {
NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
if (networkInfo != null && networkInfo.isConnected()) {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI || networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
return true;
}
}
}
}
return false;
}
private Network findVpnNetwork() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
Network[] networks = cm.getAllNetworks();
for (Network network : networks) {
LinkProperties linkProperties = cm.getLinkProperties(network);
List<LinkAddress> addresses = linkProperties.getLinkAddresses();
for (LinkAddress addr : addresses) {
if (addr.getAddress().equals(VPN_ADDRESS)) {
return network;
}
}
}
return null;
}
private static boolean isConnected(Context context, int type) {
//getAllNetworkInfo() 在 API 23 中被弃用
//getAllNetworks() 在 API 21 中才添加
ConnectivityManager manager = (ConnectivityManager) context.
getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
NetworkInfo[] allNetworkInfo = new NetworkInfo[0];
if (manager != null) {
allNetworkInfo = manager.getAllNetworkInfo();
}
for (NetworkInfo info : allNetworkInfo) {
if (info.getType() == type) {
return info.isAvailable();
}
}
} else {
Network[] networks = new Network[0];
if (manager != null) {
networks = manager.getAllNetworks();
}
for (Network network : networks) {
NetworkInfo networkInfo = manager.getNetworkInfo(network);
if (networkInfo.getType() == type) {
return networkInfo.isAvailable();
}
}
}
return false;
}
public static boolean isNetworkConnected(final Context context) {
final ConnectivityManager manager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
if (manager != null) {
final Network[] networks = manager.getAllNetworks();
if (networks != null) {
for (final Network network : networks) {
final NetworkInfo info = manager.getNetworkInfo(network);
if (info.getState() == CONNECTED) {
return true;
}
}
}
}
return false;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static boolean isAvailableSdk21(final ConnectivityManager manager,
final int networkType) {
for (final Network network : manager.getAllNetworks()) {
final NetworkInfo info = manager.getNetworkInfo(network);
if (info != null && info.isConnected() && info.getType() == networkType) {
return true;
}
}
return false;
}
@Override
@TargetApi(21)
public String[] getDnsServerAddresses() {
final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final Network[] networks = connectivityManager == null ? null : connectivityManager.getAllNetworks();
if (networks == null) {
return new String[0];
}
final Network activeNetwork = getActiveNetwork(connectivityManager);
final List<String> servers = new ArrayList<>();
int vpnOffset = 0;
for (Network network : networks) {
LinkProperties linkProperties = connectivityManager.getLinkProperties(network);
if (linkProperties == null) {
continue;
}
final NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
final boolean isActiveNetwork = network.equals(activeNetwork);
final boolean isVpn = networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_VPN;
if (isActiveNetwork && isVpn) {
final List<String> tmp = getIPv4First(linkProperties.getDnsServers());
servers.addAll(0, tmp);
vpnOffset += tmp.size();
} else if (hasDefaultRoute(linkProperties) || isActiveNetwork || activeNetwork == null || isVpn) {
servers.addAll(vpnOffset, getIPv4First(linkProperties.getDnsServers()));
}
}
return servers.toArray(new String[0]);
}
/**
* Gets the state of internet availability, whether there is no connection at all,
* whether the connection has no usage limit (like most WiFi), or whether this is
* a metered connection like most cellular plans or hotspot WiFi connections. This
* also detects whether the device has a hotspot AP enabled but the mobile
* connection does not provide internet. That is a special case that is useful
* for nearby swapping, but nothing else.
* <p>
* {@link NullPointerException}s are ignored in the hotspot detection since that
* detection should not affect normal usage at all, and there are often weird
* cases when looking through the network devices, especially on bad ROMs.
*/
public static int getNetworkState(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
if (cm == null) {
return FLAG_NET_UNAVAILABLE;
}
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork == null && Build.VERSION.SDK_INT >= 21 && cm.getAllNetworks().length == 0) {
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface netIf = networkInterfaces.nextElement();
if (netIf.getDisplayName().contains("wlan0")
|| netIf.getDisplayName().contains("eth0")
|| netIf.getDisplayName().contains("ap0")) {
for (Enumeration<InetAddress> addr = netIf.getInetAddresses(); addr.hasMoreElements();) {
InetAddress inetAddress = addr.nextElement();
if (inetAddress.isLoopbackAddress() || inetAddress instanceof Inet6Address) {
continue;
}
Log.i(TAG, "FLAG_NET_DEVICE_AP_WITHOUT_INTERNET: " + netIf.getDisplayName()
+ " " + inetAddress);
return FLAG_NET_DEVICE_AP_WITHOUT_INTERNET; // NOPMD
}
}
}
} catch (SocketException | NullPointerException e) { // NOPMD
// ignored
}
}
if (activeNetwork == null || !activeNetwork.isConnected()) {
return FLAG_NET_UNAVAILABLE;
}
int networkType = activeNetwork.getType();
switch (networkType) {
case ConnectivityManager.TYPE_ETHERNET:
case ConnectivityManager.TYPE_WIFI:
if (Build.VERSION.SDK_INT >= 16 && cm.isActiveNetworkMetered()) {
return FLAG_NET_METERED;
} else {
return FLAG_NET_NO_LIMIT;
}
default:
return FLAG_NET_METERED;
}
}
static public NetworkStatus checkConnectivity(Context context)
{
NetworkStatus networkStatus = NetworkStatus.NetworkStatusNone;
RCLogger.d(TAG, "checkConnectivity()");
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
if (activeNetwork != null) {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI && activeNetwork.isConnected()) {
RCLogger.w(TAG, "Connectivity status: WIFI");
networkStatus = NetworkStatus.NetworkStatusWiFi;
}
if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE && activeNetwork.isConnected()) {
RCLogger.w(TAG, "Connectivity status: CELLULAR DATA");
networkStatus = NetworkStatus.NetworkStatusCellular;
}
if (activeNetwork.getType() == ConnectivityManager.TYPE_ETHERNET && activeNetwork.isConnected()) {
RCLogger.w(TAG, "Connectivity status: ETHERNET");
networkStatus = NetworkStatus.NetworkStatusEthernet;
}
}
// Sadly we cannot use getActiveNetwork right away as its added in API 23 (and we want to support > 21), so let's iterate
// until we find above activeNetwork
for (Network network : connectivityManager.getAllNetworks()) {
NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
if (networkInfo.isConnected() &&
(networkInfo.getType() == activeNetwork.getType()) &&
(networkInfo.getSubtype() == activeNetwork.getSubtype()) &&
(networkInfo.getExtraInfo().equals(activeNetwork.getExtraInfo()))) {
LinkProperties linkProperties = connectivityManager.getLinkProperties(network);
//Log.d("DnsInfo", "iface = " + linkProperties.getInterfaceName());
//Log.d("DnsInfo", "dns = " + linkProperties.getDnsServers());
//Log.d("DnsInfo", "domains search = " + linkProperties.getDomains());
StringBuilder stringBuilder = new StringBuilder();
for (InetAddress inetAddress : linkProperties.getDnsServers()) {
if (stringBuilder.length() != 0) {
stringBuilder.append(",");
}
stringBuilder.append(inetAddress.getHostAddress());
}
// From Oreo and above we need to explicitly retrieve and provide the name servers used for our DNS queries.
// Reason for that is that prior to Oreo underlying dnsjava library for jain-sip.ext (i.e. providing facilities for DNS SRV),
// used some system properties prefixed 'net.dns1', etc. The problem is that those got removed in Oreo so we have to use
// alternative means, and that is to use 'dns.server' that 'dnsjava' tries to use before trying 'net.dns1';
if (stringBuilder.length() != 0) {
RCLogger.i(TAG, "Updating DNS servers for dnsjava with: " + stringBuilder.toString() + ", i/f: " + linkProperties.getInterfaceName());
System.setProperty("dns.server", stringBuilder.toString());
}
if (linkProperties.getDomains() != null) {
RCLogger.i(TAG, "Updating DNS search domains for dnsjava with: " + linkProperties.getDomains() + ", i/f: " + linkProperties.getInterfaceName());
System.setProperty("dns.search", linkProperties.getDomains());
}
}
}
}
catch (NullPointerException e) {
throw new RuntimeException("Failed to retrieve active networks info", e);
}
if (networkStatus == NetworkStatus.NetworkStatusNone) {
RCLogger.w(TAG, "Connectivity status: NONE");
}
return networkStatus;
}