如何确定Android中Wifi,3G,4G(LTE)和VPN的网络接口?
作者:互联网
在android中,我发现了网络接口名称&通过以下代码与该接口关联的IP地址.
// Iterate over all network interfaces.
for (Enumeration<NetworkInterface> en =
NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
{
NetworkInterface intf = en.nextElement();
// Iterate over all IP addresses in each network interface.
for (Enumeration<InetAddress> enumIPAddr =
intf.getInetAddresses(); enumIPAddr.hasMoreElements();)
{
InetAddress iNetAddress = enumIPAddr.nextElement();
// Loop back address (127.0.0.1) doesn't count as an in-use IP address.
if (!iNetAddress.isLoopbackAddress())
{
sLocalIP = iNetAddress.getHostAddress().toString();
sInterfaceName = intf.getName();
}
}
}
由于网络接口名称可能因制造商而异,并且在同一制造商的不同设备中也可能有所不同.
如何确定哪个网络接口适用于wifi,3G,4G(LTE)& Android中的VPN?
解决方法:
使用这种方法,您可以确定它是Wifi还是移动连接:
private static boolean isConnectedWifi(Context context) {
NetworkInfo info = ConnectionUtil.getNetworkInfo(context);
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
}
private static boolean isConnectedMobile(Context context) {
NetworkInfo info = ConnectionUtil.getNetworkInfo(context);
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE);
}
如果是移动连接,则可以通过info.getSubType()了解更多信息.使用这样的方法:
private static String getConnectionType(int type, int subType) {
if (type == ConnectivityManager.TYPE_WIFI) {
return "TYPE_WIFI";
} else if (type == ConnectivityManager.TYPE_MOBILE) {
switch (subType) {
case TelephonyManager.NETWORK_TYPE_UNKNOWN:
return "TYPE_UNKNOWN";
case TelephonyManager.NETWORK_TYPE_1xRTT:
return "TYPE_1XRTT"; // ~ 50-100 kbps
case TelephonyManager.NETWORK_TYPE_CDMA:
return "TYPE_CDMA"; // ~ 14-64 kbps
case TelephonyManager.NETWORK_TYPE_EDGE:
return "TYPE_EDGE"; // ~ 50-100 kbps
case TelephonyManager.NETWORK_TYPE_EVDO_0:
return "TYPE_EVDO_0"; // ~ 400-1000 kbps
case TelephonyManager.NETWORK_TYPE_EVDO_A:
return "TYPE_EVDO_A"; // ~ 600-1400 kbps
case TelephonyManager.NETWORK_TYPE_GPRS:
return "TYPE_GPRS"; // ~ 100 kbps
case TelephonyManager.NETWORK_TYPE_HSDPA:
return "TYPE_HSDPA"; // ~ 2-14 Mbps
case TelephonyManager.NETWORK_TYPE_HSPA:
return "TYPE_HSPA"; // ~ 700-1700 kbps
case TelephonyManager.NETWORK_TYPE_HSUPA:
return "TYPE_HSUPA"; // ~ 1-23 Mbps
case TelephonyManager.NETWORK_TYPE_UMTS:
return "TYPE_UMTS"; // ~ 400-7000 kbps
case TelephonyManager.NETWORK_TYPE_IDEN: // API level 8
return "TYPE_IDEN"; // ~25 kbps
// Unknown
default:
return "TYPE_UNKNOWN";
}
} else {
return "TYPE UNKNOWN";
}
}
希望它能对您有所帮助:)
标签:android-networking,network-interface,android 来源: https://codeday.me/bug/20191029/1959455.html