您的位置:首页 > 理论基础 > 计算机网络

android设备获取当前所用网络类型和获取手机ip地址

2015-04-24 09:32 871 查看
/**

* 得到当前的手机网络类型

*

* @param context

* @return

*/

public static String getCurrentNetType(Context context) {

String type = "";

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo info = cm.getActiveNetworkInfo();

if (info == null) {

type = "null";

} else if (info.getType() == ConnectivityManager.TYPE_WIFI) {

type = "wifi";

} else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {

int subType = info.getSubtype();

if (subType == TelephonyManager.NETWORK_TYPE_CDMA || subType == TelephonyManager.NETWORK_TYPE_GPRS

|| subType == TelephonyManager.NETWORK_TYPE_EDGE) {

type = "2g";

} else if (subType == TelephonyManager.NETWORK_TYPE_UMTS || subType == TelephonyManager.NETWORK_TYPE_HSDPA

|| subType == TelephonyManager.NETWORK_TYPE_EVDO_A || subType == TelephonyManager.NETWORK_TYPE_EVDO_0

|| subType == TelephonyManager.NETWORK_TYPE_EVDO_B) {

type = "3g";

} else if (subType == TelephonyManager.NETWORK_TYPE_LTE) {// LTE是3g到4g的过渡,是3.9G的全球标准

type = "4g";

}

}

LogProxy.d("QZY", "type=" + type);

return type;

}

/**

* 获取手机ip地址

*

* @return

*/

public static String getPhoneIp() {

try {

for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {

NetworkInterface intf = en.nextElement();

for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {

InetAddress inetAddress = enumIpAddr.nextElement();

if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {

// if (!inetAddress.isLoopbackAddress() && inetAddress

// instanceof Inet6Address) {

return inetAddress.getHostAddress().toString();

}

}

}

} catch (Exception e) {

}

return "";

}

转载自:http://www.open-open.com/lib/view/open1409190432572.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: