NetworkUtils 网络相关的工具类NetworkUtils

骑猪看日落 2022-08-23 04:58 296阅读 0赞

NetworkUtils 网络相关的工具类NetworkUtils

关于判断手机网络状态及网络管理的工具类,欢迎大家一起来添加或者批评指正, 拿走不谢~

  1. /**
  2. * 网络相关的工具类
  3. * 判断网络是否可用,wifi,数据上网开关等
  4. */
  5. public class NetworkUtils {
  6. public static final int NETWORK_TYPE_UNKNOWN = 0;
  7. public static final int NETWORK_TYPE_WIFI = 2;
  8. public static final int NETWORK_TYPE_CMWAP = 3;
  9. public static final int NETWORK_TYPE_CMNET = 4;
  10. public static final int NETWORK_TYPE_CTNET = 5;
  11. public static final int NETWORK_TYPE_CTWAP = 6;
  12. public static final int NETWORK_TYPE_3GWAP = 7;
  13. public static final int NETWORK_TYPE_3GNET = 8;
  14. public static final int NETWORK_TYPE_UNIWAP = 9;
  15. public static final int NETWORK_TYPE_UNINET = 10;
  16. private Context context;
  17. private ConnectivityManager connManager;
  18. public NetworkUtils(Context context) {
  19. this.context = context;
  20. connManager = (ConnectivityManager) this.context
  21. .getSystemService(Context.CONNECTIVITY_SERVICE);
  22. }
  23. /**
  24. * 网络是否可用
  25. *
  26. * @return
  27. */
  28. public boolean isAvailable() {
  29. final NetworkInfo[] info = connManager.getAllNetworkInfo();
  30. if (info != null)
  31. {
  32. final int size = info.length;
  33. for (int i = 0; i < size; i++)
  34. {
  35. if (info[i].getState() == NetworkInfo.State.CONNECTED)
  36. {
  37. return true;
  38. }
  39. }
  40. }
  41. return false;
  42. }
  43. /**
  44. * 网络是否连接可用
  45. *
  46. * @return
  47. */
  48. public boolean isNetworkConnected() {
  49. if (connManager == null) {
  50. connManager = (ConnectivityManager) ItLanbaoLibApplication.getInstance()
  51. .getSystemService(Context.CONNECTIVITY_SERVICE);
  52. }
  53. if (connManager != null) {
  54. final NetworkInfo networkinfo = connManager.getActiveNetworkInfo();
  55. if (networkinfo != null) {
  56. return networkinfo.isConnected();
  57. }
  58. } else {
  59. return true;
  60. }
  61. return false;
  62. }
  63. public static boolean isAvailable(Context context) {
  64. final ConnectivityManager connectivityManager = (ConnectivityManager) context
  65. .getSystemService(Context.CONNECTIVITY_SERVICE);
  66. final NetworkInfo info = connectivityManager.getActiveNetworkInfo();
  67. if (info != null && info.isAvailable()) {
  68. return true;
  69. }
  70. return false;
  71. }
  72. /**
  73. * wifi是否连接可用
  74. *
  75. * @return
  76. */
  77. public boolean isWifiConnected() {
  78. try {
  79. final NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  80. if (mWifi != null) {
  81. return mWifi.isConnected();
  82. }
  83. } catch (Exception e) {
  84. e.printStackTrace();
  85. return true;
  86. }
  87. return false;
  88. }
  89. /**
  90. * 当wifi不能访问网络时,mobile才会起作用
  91. *
  92. * @return GPRS是否连接可用
  93. */
  94. public boolean isMobileConnected() {
  95. final NetworkInfo mMobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
  96. if (mMobile != null) {
  97. return mMobile.isConnected();
  98. }
  99. return false;
  100. }
  101. /**
  102. * GPRS网络开关 反射ConnectivityManager中hide的方法setMobileDataEnabled 可以开启和关闭GPRS网络
  103. *
  104. * @param isEnable
  105. * @throws Exception
  106. */
  107. public void toggleGprs(boolean isEnable) throws Exception {
  108. final Class<?> cmClass = connManager.getClass();
  109. final Class<?>[] argClasses = new Class[1];
  110. argClasses[0] = boolean.class;
  111. // 反射ConnectivityManager中hide的方法setMobileDataEnabled,可以开启和关闭GPRS网络
  112. final Method method = cmClass.getMethod("setMobileDataEnabled", argClasses);
  113. method.invoke(connManager, isEnable);
  114. }
  115. /**
  116. * WIFI网络开关
  117. *
  118. * @param enabled
  119. * @return 设置是否success
  120. */
  121. public boolean toggleWiFi(boolean enabled) {
  122. final WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
  123. return wm.setWifiEnabled(enabled);
  124. }
  125. /**
  126. * 获取网络类型
  127. * @param context
  128. * @return
  129. */
  130. public static String getNetworkType(Context context) {
  131. final ConnectivityManager connectivityManager = (ConnectivityManager) context
  132. .getSystemService(Context.CONNECTIVITY_SERVICE);
  133. final NetworkInfo mobNetInfoActivity = connectivityManager
  134. .getActiveNetworkInfo();
  135. if (mobNetInfoActivity == null) {
  136. return "";
  137. }
  138. String netTypeMode = "";
  139. final int netType = mobNetInfoActivity.getType();
  140. if (netType == ConnectivityManager.TYPE_WIFI) {
  141. // wifi上网
  142. netTypeMode = "wifi";
  143. } else if (netType == ConnectivityManager.TYPE_MOBILE) {
  144. // 接入点上网
  145. final String netMode = mobNetInfoActivity.getExtraInfo();
  146. if (!TextUtils.isEmpty(netMode)) {
  147. return netMode;
  148. }
  149. {/* 由于4.0以上版本手机禁用了android.permission.WRITE_APN_SETTINGS权限,所以以下代码不可用
  150. // 获取当前设置的APN
  151. private static final Uri CURRENT_APN_URI = Uri.parse("content://telephony/carriers/preferapn");
  152. // 如果netMode没有获取到,则从数据库中查找当前使用的接入点
  153. final Cursor c = context.getContentResolver().query(
  154. CURRENT_APN_URI, null, null, null, null);
  155. if (c != null) {
  156. c.moveToFirst();
  157. final String apn = c.getString(c.getColumnIndex("apn"));
  158. if (!TextUtils.isEmpty(apn)) {
  159. netTypeMode = apn;
  160. }
  161. c.close();
  162. }
  163. */}
  164. }
  165. return netTypeMode;
  166. }
  167. /**
  168. * 获取网络类型id
  169. * @param context
  170. *
  171. * @return 0:无网络,2:wifi、3:cmwap、4:cmnet、5:ctnet、6:ctwap、7:3gwap、8:3gnet、9:uniwap、10:uninet
  172. */
  173. // public static int getNetworkTypeId(Context context)
  174. // {
  175. // final String type = getNetworkType(context);
  176. // if ("wifi".equalsIgnoreCase(type)) {
  177. // return NETWORK_TYPE_WIFI;
  178. // } else if ("cmwap".equalsIgnoreCase(type)) {
  179. // return NETWORK_TYPE_CMWAP;
  180. // } else if ("cmnet".equalsIgnoreCase(type)) {
  181. // return NETWORK_TYPE_CMNET;
  182. // } else if ("ctnet".equalsIgnoreCase(type)) {
  183. // return NETWORK_TYPE_CTNET;
  184. // } else if ("ctwap".equalsIgnoreCase(type)) {
  185. // return NETWORK_TYPE_CTWAP;
  186. // } else if ("3gwap".equalsIgnoreCase(type)) {
  187. // return NETWORK_TYPE_3GWAP;
  188. // } else if ("3gnet".equalsIgnoreCase(type)) {
  189. // return NETWORK_TYPE_3GNET;
  190. // } else if ("uniwap".equalsIgnoreCase(type)) {
  191. // return NETWORK_TYPE_UNIWAP;
  192. // } else if ("uninet".equalsIgnoreCase(type)) {
  193. // return NETWORK_TYPE_UNINET;
  194. // }
  195. // return NETWORK_TYPE_UNKNOWN;
  196. // }
  197. /**
  198. * 获取网络类型id
  199. * @param context
  200. *
  201. * @return 0:无网络,2:wifi,11:2G网络,12:3G网络,13:4G网络
  202. */
  203. public static int getNetworkTypeId(Context context)
  204. {
  205. // String strNetworkType = "";
  206. int strNetworkType = 0;
  207. NetworkInfo networkInfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
  208. if (networkInfo != null && networkInfo.isConnected())
  209. {
  210. if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI)
  211. {
  212. // strNetworkType = "WIFI";
  213. strNetworkType = 2;
  214. }
  215. else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
  216. {
  217. String _strSubTypeName = networkInfo.getSubtypeName();
  218. if (LogUtils.DEBUG) {
  219. LogUtils.e("cocos2d-x", "Network getSubtypeName : " + _strSubTypeName);
  220. }
  221. // TD-SCDMA networkType is 17
  222. int networkType = networkInfo.getSubtype();
  223. switch (networkType) {
  224. case TelephonyManager.NETWORK_TYPE_GPRS:
  225. case TelephonyManager.NETWORK_TYPE_EDGE:
  226. case TelephonyManager.NETWORK_TYPE_CDMA:
  227. case TelephonyManager.NETWORK_TYPE_1xRTT:
  228. case TelephonyManager.NETWORK_TYPE_IDEN: //api<8 : replace by 11
  229. // strNetworkType = "2G";
  230. strNetworkType = 11;
  231. break;
  232. case TelephonyManager.NETWORK_TYPE_UMTS:
  233. case TelephonyManager.NETWORK_TYPE_EVDO_0:
  234. case TelephonyManager.NETWORK_TYPE_EVDO_A:
  235. case TelephonyManager.NETWORK_TYPE_HSDPA:
  236. case TelephonyManager.NETWORK_TYPE_HSUPA:
  237. case TelephonyManager.NETWORK_TYPE_HSPA:
  238. case TelephonyManager.NETWORK_TYPE_EVDO_B: //api<9 : replace by 14
  239. case TelephonyManager.NETWORK_TYPE_EHRPD: //api<11 : replace by 12
  240. case TelephonyManager.NETWORK_TYPE_HSPAP: //api<13 : replace by 15
  241. // strNetworkType = "3G";
  242. strNetworkType = 12;
  243. break;
  244. case TelephonyManager.NETWORK_TYPE_LTE: //api<11 : replace by 13
  245. // strNetworkType = "4G";
  246. strNetworkType = 13;
  247. break;
  248. default:
  249. // http://baike.baidu.com/item/TD-SCDMA 中国移动 联通 电信 三种3G制式
  250. if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA") || _strSubTypeName.equalsIgnoreCase("WCDMA") || _strSubTypeName.equalsIgnoreCase("CDMA2000"))
  251. {
  252. // strNetworkType = "3G";
  253. strNetworkType = 12;
  254. }
  255. else
  256. {
  257. // strNetworkType = _strSubTypeName;
  258. strNetworkType = 0;
  259. }
  260. break;
  261. }
  262. if (LogUtils.DEBUG) {
  263. LogUtils.e("cocos2d-x", "Network getSubtype : " + Integer.valueOf(networkType).toString());
  264. }
  265. }
  266. }
  267. if (LogUtils.DEBUG) {
  268. LogUtils.e("cocos2d-x", "Network Type : " + strNetworkType);
  269. }
  270. return strNetworkType;
  271. }
  272. /**
  273. * 获取ip地址
  274. * @return
  275. */
  276. public static String getLocalIpAddress() {
  277. try {
  278. for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
  279. NetworkInterface intf = en.nextElement();
  280. for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
  281. InetAddress inetAddress = enumIpAddr.nextElement();
  282. if (!inetAddress.isLoopbackAddress()
  283. && inetAddress instanceof Inet4Address) {
  284. return inetAddress.getHostAddress().toString();
  285. }
  286. }
  287. }
  288. } catch (Exception ex) {
  289. ex.printStackTrace();
  290. }
  291. return "";
  292. }
  293. /**
  294. * 设置网络,主要是判断是否使用WAP连接
  295. */
  296. public static void setupNetwork(Context context, HttpClient httpClient) {
  297. if (isUsingWap(context)) {
  298. final String host = Proxy.getDefaultHost();
  299. final int port = Proxy.getDefaultPort();
  300. if (!TextUtils.isEmpty(host) && port != -1) {
  301. final HttpHost proxy = new HttpHost(host, port);
  302. httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
  303. }
  304. }
  305. }
  306. /**
  307. * 判断是否使用WAP连接
  308. */
  309. public static boolean isUsingWap(Context context) {
  310. boolean result = false;
  311. if (isNetworkAvailable(context) && getNetworkConnectType(context) == NetworkConnectType.MOBILE) {
  312. final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  313. final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
  314. if (networkInfo != null) {
  315. final String netExtraInfo = networkInfo.getExtraInfo();
  316. if (LogUtils.DEBUG) {
  317. LogUtils.e("getFromHttp netExtraInfo " + netExtraInfo);
  318. }
  319. if (!TextUtils.isEmpty(netExtraInfo) && netExtraInfo.toLowerCase().contains("wap")) {
  320. result = true;
  321. }
  322. }
  323. }
  324. return result;
  325. }
  326. /**
  327. * 判断网络是否可用
  328. */
  329. public static boolean isNetworkAvailable(Context context) {
  330. boolean result = false;
  331. ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  332. if (connectivityManager != null) {
  333. NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo();
  334. if (networkInfos != null) {
  335. final int length = networkInfos.length;
  336. for (int i = 0; i < length; i++) {
  337. if (networkInfos[i].getState() == NetworkInfo.State.CONNECTED) {
  338. return true;
  339. }
  340. }
  341. }
  342. }
  343. return result;
  344. }
  345. /**
  346. * 获得当前网络连接类型
  347. */
  348. public static NetworkConnectType getNetworkConnectType(Context context) {
  349. NetworkConnectType networkConnectType = null;
  350. final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  351. if (connectivityManager != null) {
  352. // mobile
  353. final NetworkInfo mobile = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
  354. // wifi
  355. final NetworkInfo wifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  356. if (mobile != null && (mobile.getState() == NetworkInfo.State.CONNECTED || mobile.getState() == NetworkInfo.State.CONNECTING)) {
  357. // mobile
  358. networkConnectType = NetworkConnectType.MOBILE;
  359. } else if (wifi != null && (wifi.getState() == NetworkInfo.State.CONNECTED || wifi.getState() == NetworkInfo.State.CONNECTING)) {
  360. // wifi
  361. networkConnectType = NetworkConnectType.WIFI;
  362. }
  363. }
  364. return networkConnectType;
  365. }
  366. /**
  367. * 网络连接枚举类型
  368. */
  369. public enum NetworkConnectType {
  370. MOBILE, WIFI
  371. }
  372. }

发表评论

表情:
评论列表 (有 0 条评论,296人围观)

还没有评论,来说两句吧...

相关阅读