-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNetStatusUtil.java
87 lines (82 loc) · 3.4 KB
/
NetStatusUtil.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
public class NetStatusUtil {
/**
* 检测当前打开的网络类型是否WIFI
*
* @param context 上下文
* @return 是否是Wifi上网
*/
public static boolean isWifi(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context
.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
}
return false;
}
/**
* 是否有网
*/
public static boolean isConnected(Context context) {
return netStatus(context) != NetState.NET_NO;
}
/**
* 枚举网络状态 NET_NO:没有网络 NET_2G:2g网络 NET_3G:3g网络 NET_4G:4g网络 NET_WIFI:wifi
* NET_UNKNOWN:未知网络
*/
public static enum NetState {
NET_NO, NET_2G, NET_3G, NET_4G, NET_WIFI, NET_UNKNOWN
}
/**
* 判断当前是否网络连接
*
* @param context 上下文
* @return 状态码
*/
public static NetState netStatus(Context context) {
NetState stateCode = NetState.NET_NO;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.isConnectedOrConnecting()) {
switch (ni.getType()) {
case ConnectivityManager.TYPE_WIFI:
stateCode = NetState.NET_WIFI;
break;
case ConnectivityManager.TYPE_MOBILE:
switch (ni.getSubtype()) {
case TelephonyManager.NETWORK_TYPE_GPRS: // 联通2g
case TelephonyManager.NETWORK_TYPE_CDMA: // 电信2g
case TelephonyManager.NETWORK_TYPE_EDGE: // 移动2g
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN:
stateCode = NetState.NET_2G;
break;
case TelephonyManager.NETWORK_TYPE_EVDO_A: // 电信3g
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
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:
stateCode = NetState.NET_3G;
break;
case TelephonyManager.NETWORK_TYPE_LTE:
stateCode = NetState.NET_4G;
break;
default:
stateCode = NetState.NET_UNKNOWN;
}
break;
default:
stateCode = NetState.NET_UNKNOWN;
}
}
return stateCode;
}
}