-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNetworkUtils.java
348 lines (322 loc) · 13 KB
/
NetworkUtils.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package com.common.utilcode.util;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* <pre>
* author: Mayank Dudhatra
* blog : androidroadies.blogspot.in
* time : 2016/08/02
* desc : 网络相关工具类
* </pre>
*/
public final class NetworkUtils {
private NetworkUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
public enum NetworkType {
NETWORK_WIFI,
NETWORK_4G,
NETWORK_3G,
NETWORK_2G,
NETWORK_UNKNOWN,
NETWORK_NO
}
/**
* 打开网络设置界面
* <p>3.0以下打开设置界面</p>
*/
public static void openWirelessSettings() {
if (android.os.Build.VERSION.SDK_INT > 10) {
Utils.getContext().startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
} else {
Utils.getContext().startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
}
/**
* 获取活动网络信息
* <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}</p>
*
* @return NetworkInfo
*/
private static NetworkInfo getActiveNetworkInfo() {
return ((ConnectivityManager) Utils.getContext().getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
}
/**
* 判断网络是否连接
* <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}</p>
*
* @return {@code true}: 是<br>{@code false}: 否
*/
public static boolean isConnected() {
NetworkInfo info = getActiveNetworkInfo();
return info != null && info.isConnected();
}
/**
* 判断网络是否可用
* <p>需添加权限 {@code <uses-permission android:name="android.permission.INTERNET"/>}</p>
*
* @return {@code true}: 可用<br>{@code false}: 不可用
*/
public static boolean isAvailableByPing() {
ShellUtils.CommandResult result = ShellUtils.execCmd("ping -c 1 -w 1 223.5.5.5", false);
boolean ret = result.result == 0;
if (result.errorMsg != null) {
LogUtils.d("isAvailableByPing errorMsg", result.errorMsg);
}
if (result.successMsg != null) {
LogUtils.d("isAvailableByPing successMsg", result.successMsg);
}
return ret;
}
/**
* 判断移动数据是否打开
*
* @return {@code true}: 是<br>{@code false}: 否
*/
public static boolean getDataEnabled() {
try {
TelephonyManager tm = (TelephonyManager) Utils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
Method getMobileDataEnabledMethod = tm.getClass().getDeclaredMethod("getDataEnabled");
if (null != getMobileDataEnabledMethod) {
return (boolean) getMobileDataEnabledMethod.invoke(tm);
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 打开或关闭移动数据
* <p>需系统应用 需添加权限{@code <uses-permission android:name="android.permission.MODIFY_PHONE_STATE"/>}</p>
*
* @param enabled {@code true}: 打开<br>{@code false}: 关闭
*/
public static void setDataEnabled(boolean enabled) {
try {
TelephonyManager tm = (TelephonyManager) Utils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
Method setMobileDataEnabledMethod = tm.getClass().getDeclaredMethod("setDataEnabled", boolean.class);
if (null != setMobileDataEnabledMethod) {
setMobileDataEnabledMethod.invoke(tm, enabled);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 判断网络是否是4G
* <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}</p>
*
* @return {@code true}: 是<br>{@code false}: 否
*/
public static boolean is4G() {
NetworkInfo info = getActiveNetworkInfo();
return info != null && info.isAvailable() && info.getSubtype() == TelephonyManager.NETWORK_TYPE_LTE;
}
/**
* 判断wifi是否打开
* <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>}</p>
*
* @return {@code true}: 是<br>{@code false}: 否
*/
public static boolean getWifiEnabled() {
@SuppressLint("WifiManagerLeak")
WifiManager wifiManager = (WifiManager) Utils.getContext().getSystemService(Context.WIFI_SERVICE);
return wifiManager.isWifiEnabled();
}
/**
* 打开或关闭wifi
* <p>需添加权限 {@code <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>}</p>
*
* @param enabled {@code true}: 打开<br>{@code false}: 关闭
*/
public static void setWifiEnabled(boolean enabled) {
@SuppressLint("WifiManagerLeak")
WifiManager wifiManager = (WifiManager) Utils.getContext().getSystemService(Context.WIFI_SERVICE);
if (enabled) {
if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
}
} else {
if (wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(false);
}
}
}
/**
* 判断wifi是否连接状态
* <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}</p>
*
* @return {@code true}: 连接<br>{@code false}: 未连接
*/
public static boolean isWifiConnected() {
ConnectivityManager cm = (ConnectivityManager) Utils.getContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm != null && cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;
}
/**
* 判断wifi数据是否可用
* <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>}</p>
* <p>需添加权限 {@code <uses-permission android:name="android.permission.INTERNET"/>}</p>
*
* @return {@code true}: 是<br>{@code false}: 否
*/
public static boolean isWifiAvailable() {
return getWifiEnabled() && isAvailableByPing();
}
/**
* 获取网络运营商名称
* <p>中国移动、如中国联通、中国电信</p>
*
* @return 运营商名称
*/
public static String getNetworkOperatorName() {
TelephonyManager tm = (TelephonyManager) Utils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
return tm != null ? tm.getNetworkOperatorName() : null;
}
private static final int NETWORK_TYPE_GSM = 16;
private static final int NETWORK_TYPE_TD_SCDMA = 17;
private static final int NETWORK_TYPE_IWLAN = 18;
/**
* 获取当前网络类型
* <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}</p>
*
* @return 网络类型
* <ul>
* <li>{@link NetworkUtils.NetworkType#NETWORK_WIFI } </li>
* <li>{@link NetworkUtils.NetworkType#NETWORK_4G } </li>
* <li>{@link NetworkUtils.NetworkType#NETWORK_3G } </li>
* <li>{@link NetworkUtils.NetworkType#NETWORK_2G } </li>
* <li>{@link NetworkUtils.NetworkType#NETWORK_UNKNOWN} </li>
* <li>{@link NetworkUtils.NetworkType#NETWORK_NO } </li>
* </ul>
*/
public static NetworkType getNetworkType() {
NetworkType netType = NetworkType.NETWORK_NO;
NetworkInfo info = getActiveNetworkInfo();
if (info != null && info.isAvailable()) {
if (info.getType() == ConnectivityManager.TYPE_WIFI) {
netType = NetworkType.NETWORK_WIFI;
} else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
switch (info.getSubtype()) {
case NETWORK_TYPE_GSM:
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN:
netType = NetworkType.NETWORK_2G;
break;
case NETWORK_TYPE_TD_SCDMA:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
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:
netType = NetworkType.NETWORK_3G;
break;
case NETWORK_TYPE_IWLAN:
case TelephonyManager.NETWORK_TYPE_LTE:
netType = NetworkType.NETWORK_4G;
break;
default:
String subtypeName = info.getSubtypeName();
if (subtypeName.equalsIgnoreCase("TD-SCDMA")
|| subtypeName.equalsIgnoreCase("WCDMA")
|| subtypeName.equalsIgnoreCase("CDMA2000")) {
netType = NetworkType.NETWORK_3G;
} else {
netType = NetworkType.NETWORK_UNKNOWN;
}
break;
}
} else {
netType = NetworkType.NETWORK_UNKNOWN;
}
}
return netType;
}
/**
* 获取IP地址
* <p>需添加权限 {@code <uses-permission android:name="android.permission.INTERNET"/>}</p>
*
* @param useIPv4 是否用IPv4
* @return IP地址
*/
public static String getIPAddress(boolean useIPv4) {
try {
for (Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); nis.hasMoreElements(); ) {
NetworkInterface ni = nis.nextElement();
// 防止小米手机返回10.0.2.15
if (!ni.isUp()) continue;
for (Enumeration<InetAddress> addresses = ni.getInetAddresses(); addresses.hasMoreElements(); ) {
InetAddress inetAddress = addresses.nextElement();
if (!inetAddress.isLoopbackAddress()) {
String hostAddress = inetAddress.getHostAddress();
boolean isIPv4 = hostAddress.indexOf(':') < 0;
if (useIPv4) {
if (isIPv4) return hostAddress;
} else {
if (!isIPv4) {
int index = hostAddress.indexOf('%');
return index < 0 ? hostAddress.toUpperCase() : hostAddress.substring(0, index).toUpperCase();
}
}
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取域名ip地址
* <p>需添加权限 {@code <uses-permission android:name="android.permission.INTERNET"/>}</p>
*
* @param domain 域名
* @return ip地址
*/
public static String getDomainAddress(final String domain) {
try {
ExecutorService exec = Executors.newCachedThreadPool();
Future<String> fs = exec.submit(new Callable<String>() {
@Override
public String call() throws Exception {
InetAddress inetAddress;
try {
inetAddress = InetAddress.getByName(domain);
return inetAddress.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return null;
}
});
return fs.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return null;
}
}