在Android中,可以通过ConnectivityManager
和NetworkInfo
类,判断手机目前正在使用的网络类型。以下给出示例代码:
public String getNetworkType(Context context) {
String strNetworkType = "";
NetworkInfo networkInfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
strNetworkType = "WIFI";
} else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
String _strSubTypeName = networkInfo.getSubtypeName();
//如果是2G类型
if (_strSubTypeName.equalsIgnoreCase("GSM") || _strSubTypeName.equalsIgnoreCase("CDMA")
|| _strSubTypeName.equalsIgnoreCase("EDGE") || _strSubTypeName.equalsIgnoreCase("1xRTT")
|| _strSubTypeName.equalsIgnoreCase("IDEN")) {
strNetworkType = "2G";
}
//如果是3G类型
else if (_strSubTypeName.equalsIgnoreCase("UMTS") || _strSubTypeName.equalsIgnoreCase("EVDO_0")
|| _strSubTypeName.equalsIgnoreCase("EVDO_A") || _strSubTypeName.equalsIgnoreCase("HSDPA")
|| _strSubTypeName.equalsIgnoreCase("HSUPA") || _strSubTypeName.equalsIgnoreCase("HSPA")
|| _strSubTypeName.equalsIgnoreCase("EVDO_B") || _strSubTypeName.equalsIgnoreCase("EHRPD")
|| _strSubTypeName.equalsIgnoreCase("HSPAP")) {
strNetworkType = "3G";
}
//如果是4G类型
else if (_strSubTypeName.equalsIgnoreCase("LTE") || _strSubTypeName.equalsIgnoreCase("UMB")
|| _strSubTypeName.equalsIgnoreCase("HSPA+")) {
strNetworkType = "4G";
}
//Unknown
else {
strNetworkType = _strSubTypeName;
}
}
}
return strNetworkType;
}
请注意,这些代码需要ACCESS_NETWORK_STATE
权限,因此请在您的manifest.xml中添加此行:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
上述代码主要是使用了ConnectivityManager来获取当前活跃的网络连接信息,然后通过判断网络类型和子类型名称来判断手机正在使用的具体网络类型。
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/170528.html