android判断正在使用的网络类型 0.不知道网络类型;1、2G;2、3G;3、4g;4、wifi

时间:2024-01-09 20:16:56

判断正在使用的网络类型 0.不知道网络类型;1、2G;2、3G;3、4g;4、wifi

     /** Unknown network class. {@hide} */
public static final String NETWORK_CLASS_UNKNOWN = "0";
/** Class of broadly defined "2G" networks. {@hide} */
public static final String NETWORK_CLASS_2_G = "1";
/** Class of broadly defined "3G" networks. {@hide} */
public static final String NETWORK_CLASS_3_G = "2";
/** Class of broadly defined "4G" networks. {@hide} */
public static final String NETWORK_CLASS_4_G = "3";
/** Class of broadly defined "wifi" networks. {@hide} */
public static final String NETWORK_CLASS_WIFI = "4";
/**
* 判断正在使用的网络类型 0.不知道网络类型;1、2G;2、3G;3、4g;4、wifi
* @param context
* @return
*/
public static String getNet(Context context) {
try {
ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
State mobile = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
State wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
if(mobile == State.CONNECTED||mobile==State.CONNECTING) {
NetworkInfo info = manager.getActiveNetworkInfo();
int type = info.getSubtype();
switch (type) {
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN:
return NETWORK_CLASS_2_G;
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B:
case TelephonyManager.NETWORK_TYPE_EHRPD:
case TelephonyManager.NETWORK_TYPE_HSPAP:
return NETWORK_CLASS_3_G;
case TelephonyManager.NETWORK_TYPE_LTE:
return NETWORK_CLASS_4_G;
default:
return NETWORK_CLASS_UNKNOWN;
}
}
else if(wifi == State.CONNECTED||wifi==State.CONNECTING) {
return NETWORK_CLASS_WIFI;
}
} catch (Exception e) {
LogUtil.e(tag, e);
return NETWORK_CLASS_UNKNOWN;
}
return NETWORK_CLASS_UNKNOWN;
}