无网不进  
软硬件开发

NetworkUtils 网络相关的工具类NetworkUtils

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

 

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