content: package cn.hotapk.fastandrutils.utils;
  
  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.io.UnsupportedEncodingException;
  import java.lang.reflect.Method;
  import java.net.InetAddress;
  import java.net.NetworkInterface;
  import java.net.SocketException;
  import java.net.URLDecoder;
  import java.net.UnknownHostException;
  import java.util.Enumeration;
  import java.util.HashMap;
  import java.util.Map;
  
  /**
   * @author laijian
   * @version 2017/9/15
   * @Copyright (C)下午2:09 , www.hotapk.cn
   * <p>
   * 网络类
   */
  public final class FNetworkUtils {
  
      private FNetworkUtils() {
  
      }
  
      /**
       * 打开网络设置界面
       */
      public static void openWirelessSettings() {
          FUtils.getAppContext().startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_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) FUtils.getAppContext().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>中国移动、如中国联通、中国电信</p>
       *
       * @return 运营商名称
       */
      public static String getNetworkOperatorName() {
          TelephonyManager tm = (TelephonyManager) FUtils.getAppContext().getSystemService(Context.TELEPHONY_SERVICE);
          return tm != null ? tm.getNetworkOperatorName() : null;
      }
  
      /**
       * 判断网络连接是否打开,包括移动数据连接
       *
       * @return 是否联网
       */
      public static boolean isNetworkAvailable() {
          boolean netstate = false;
          ConnectivityManager connectivity = (ConnectivityManager) FUtils.getAppContext()
                  .getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null) {
  
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null) {
                  for (int i = 0; i < info.length; i++) {
  
                      if (info[i].getState() == NetworkInfo.State.CONNECTED) {
  
                          netstate = true;
                          break;
                      }
                  }
              }
          }
          return netstate;
      }
  
  
      /**
       * 检测当前打开的网络类型是否WIFI
       *
       * @return 是否是Wifi上网
       */
      public static boolean isWifi() {
          ConnectivityManager connectivityManager = (ConnectivityManager) FUtils.getAppContext()
                  .getSystemService(Context.CONNECTIVITY_SERVICE);
          NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
          return activeNetInfo != null
                  && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI;
      }
  
      /**
       * 检测当前打开的网络类型是否3G
       *
       * @return 是否是3G上网
       */
      public static boolean is3G() {
          ConnectivityManager connectivityManager = (ConnectivityManager) FUtils.getAppContext()
                  .getSystemService(Context.CONNECTIVITY_SERVICE);
          NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
          return activeNetInfo != null
                  && activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE;
      }
  
      /**
       * 检测当前开打的网络类型是否4G
       *
       * @return 是否是4G上网
       */
      public static boolean is4G() {
          ConnectivityManager connectivityManager = (ConnectivityManager) FUtils.getAppContext()
                  .getSystemService(Context.CONNECTIVITY_SERVICE);
          NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
          if (activeNetInfo != null && activeNetInfo.isConnectedOrConnecting()) {
              if (activeNetInfo.getType() == TelephonyManager.NETWORK_TYPE_LTE) {
                  return true;
              }
          }
          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(final boolean enabled) {
          try {
              TelephonyManager tm = (TelephonyManager) FUtils.getAppContext().getSystemService(Context.TELEPHONY_SERVICE);
              Method setMobileDataEnabledMethod = tm.getClass().getDeclaredMethod("setDataEnabled", boolean.class);
              if (null != setMobileDataEnabledMethod) {
                  setMobileDataEnabledMethod.invoke(tm, enabled);
              }
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
  
      /**
       * 打开或关闭wifi
       * <p>需添加权限 {@code <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>}</p>
       *
       * @param enabled {@code true}: 打开<br>{@code false}: 关闭
       */
      public static void setWifiEnabled(final boolean enabled) {
          WifiManager wifiManager = (WifiManager) FUtils.getAppContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
          if (enabled) {
              if (!wifiManager.isWifiEnabled()) {
                  wifiManager.setWifiEnabled(true);
              }
          } else {
              if (wifiManager.isWifiEnabled()) {
                  wifiManager.setWifiEnabled(false);
              }
          }
      }
  
      /**
       * 获取URL中参数 并返回Map
       *
       * @param url
       * @return
       */
      public static Map<String, String> getUrlParams(String url) {
          Map<String, String> params = null;
          try {
              String[] urlParts = url.split("\\?");
              if (urlParts.length > 1) {
                  params = new HashMap<>();
                  String query = urlParts[1];
                  for (String param : query.split("&")) {
                      String[] pair = param.split("=");
                      String key = URLDecoder.decode(pair[0], "UTF-8");
                      String value = "";
                      if (pair.length > 1) {
                          value = URLDecoder.decode(pair[1], "UTF-8");
                      }
                      params.put(key, value);
                  }
              }
          } catch (UnsupportedEncodingException ex) {
              ex.printStackTrace();
          }
          return params;
      }
  
      /**
       * 获取ip地址
       */
      public static String getIPAddress() {
          WifiManager wifiManager = (WifiManager) FUtils.getAppContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
          int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
          final String formatedIpAddress = String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
          return formatedIpAddress;
      }
  
      /**
       * 获取IP地址
       * <p>需添加权限 {@code <uses-permission android:name="android.permission.INTERNET"/>}</p>
       *
       * @param useIPv4 是否用IPv4
       * @return IP地址
       */
      public static String getIPAddress(final 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) {
          InetAddress inetAddress;
          try {
              inetAddress = InetAddress.getByName(domain);
              return inetAddress.getHostAddress();
          } catch (UnknownHostException e) {
              e.printStackTrace();
              return null;
          }
      }
  
      /**
       * 判断当前是否网络连接
       *
       * @return 状态码
       */
      public NetState getNetworkType() {
          NetState stateCode = NetState.NET_NO;
          ConnectivityManager cm = (ConnectivityManager) FUtils.getAppContext()
                  .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;
      }
  
      /**
       * 枚举网络状态 NET_NO：没有网络 NET_2G:2g网络 NET_3G：3g网络 NET_4G：4g网络 NET_WIFI：wifi
       * NET_UNKNOWN：未知网络
       */
      public enum NetState {
          NET_NO, NET_2G, NET_3G, NET_4G, NET_WIFI, NET_UNKNOWN
      }
  
  }