XYLibrary笔记九:XNewWork使用笔记

2023-03-24 13:38:57 浏览数 (1)

一.代码

XTester-network xlib-Network

二.demo

三.方法

打开网络设置界面
代码语言:javascript复制
/**
 * Open the settings of wireless.
 */
public static void openWirelessSettings() {
    getApp().startActivity(
            new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS)
                    .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    );
}
判断网络是否连接
代码语言:javascript复制
@RequiresPermission(ACCESS_NETWORK_STATE)
public static boolean isConnected() {
    NetworkInfo info = getActiveNetworkInfo();
    return info != null && info.isConnected();
}
@RequiresPermission(ACCESS_NETWORK_STATE)
private static NetworkInfo getActiveNetworkInfo() {
    ConnectivityManager cm =
            (ConnectivityManager) getApp().getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm == null) return null;
    return cm.getActiveNetworkInfo();
}
判断网络是否可用
代码语言:javascript复制
@RequiresPermission(INTERNET)
public static boolean isAvailableByDns(final String domain) {
    final String realDomain = TextUtils.isEmpty(domain) ? "www.baidu.com" : domain;
    InetAddress inetAddress;
    try {
        inetAddress = InetAddress.getByName(realDomain);
        return inetAddress != null;
    } catch (UnknownHostException e) {
        e.printStackTrace();
        return false;
    }
}
判断移动数据是否打开
代码语言:javascript复制
@RequiresPermission(MODIFY_PHONE_STATE)
public static boolean getMobileDataEnabled() {
    try {
        TelephonyManager tm =
                (TelephonyManager) getApp().getSystemService(Context.TELEPHONY_SERVICE);
        if (tm == null) return false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)  {
                return tm.isDataEnabled();
        }
        @SuppressLint("PrivateApi")
        Method getMobileDataEnabledMethod =
                tm.getClass().getDeclaredMethod("getDataEnabled");
        if (null != getMobileDataEnabledMethod) {
            return (boolean) getMobileDataEnabledMethod.invoke(tm);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
判断网络是否是移动数据
代码语言:javascript复制
@RequiresPermission(ACCESS_NETWORK_STATE)
public static boolean isMobileData() {
    NetworkInfo info = getActiveNetworkInfo();
    return null != info
            && info.isAvailable()
            && info.getType() == ConnectivityManager.TYPE_MOBILE;
}
判断网络是否是 4G、5G
代码语言:javascript复制
/**
 * Return whether using 4G.
 * <p>Must hold {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />}</p>
 *
 * @return {@code true}: yes<br>{@code false}: no
 */
@RequiresPermission(ACCESS_NETWORK_STATE)
public static boolean is4G() {
    NetworkInfo info = getActiveNetworkInfo();
    return info != null
            && info.isAvailable()
            && info.getSubtype() == TelephonyManager.NETWORK_TYPE_LTE;
}

/**
 * Return whether using 4G.
 * <p>Must hold {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />}</p>
 *
 * @return {@code true}: yes<br>{@code false}: no
 */
@RequiresPermission(ACCESS_NETWORK_STATE)
public static boolean is5G() {
    NetworkInfo info = getActiveNetworkInfo();
    return info != null
            && info.isAvailable()
            && info.getSubtype() == TelephonyManager.NETWORK_TYPE_NR;
}

@RequiresPermission(ACCESS_NETWORK_STATE)
private static NetworkInfo getActiveNetworkInfo() {
    ConnectivityManager cm =
            (ConnectivityManager) getApp().getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm == null) return null;
    return cm.getActiveNetworkInfo();
}
判断 wifi 是否打开
代码语言:javascript复制
@RequiresPermission(ACCESS_WIFI_STATE)
public static boolean getWifiEnabled() {
    @SuppressLint("WifiManagerLeak")
    WifiManager manager = (WifiManager) getApp().getSystemService(WIFI_SERVICE);
    if (manager == null) return false;
    return manager.isWifiEnabled();
}
打开或关闭 wifi
代码语言:javascript复制
@RequiresPermission(CHANGE_WIFI_STATE)
public static void setWifiEnabled(final boolean enabled) {
    @SuppressLint("WifiManagerLeak")
    WifiManager manager = (WifiManager) getApp().getSystemService(WIFI_SERVICE);
    if (manager == null) return;
    if (enabled == manager.isWifiEnabled()) return;
    manager.setWifiEnabled(enabled);
}
判断 wifi 是否连接状态
代码语言:javascript复制
@RequiresPermission(ACCESS_NETWORK_STATE)
public static boolean isWifiConnected() {
    ConnectivityManager cm =
            (ConnectivityManager) getApp().getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm == null) return false;
    NetworkInfo ni = cm.getActiveNetworkInfo();
    return ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI;
}
获取当前网络类型
代码语言:javascript复制
@RequiresPermission(ACCESS_NETWORK_STATE)
public static NetworkType getNetworkType() {
    if (isEthernet()) {
        return NetworkType.NETWORK_ETHERNET;
    }
    NetworkInfo info = getActiveNetworkInfo();
    if (info != null && info.isAvailable()) {
        if (info.getType() == ConnectivityManager.TYPE_WIFI) {
            return NetworkType.NETWORK_WIFI;
        } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
            switch (info.getSubtype()) {
                case TelephonyManager.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:
                    return NetworkType.NETWORK_2G;

                case TelephonyManager.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:
                    return NetworkType.NETWORK_3G;

                case TelephonyManager.NETWORK_TYPE_IWLAN:
                case TelephonyManager.NETWORK_TYPE_LTE:
                    return NetworkType.NETWORK_4G;

                case TelephonyManager.NETWORK_TYPE_NR:
                    return NetworkType.NETWORK_5G;
                default:
                    String subtypeName = info.getSubtypeName();
                    if (subtypeName.equalsIgnoreCase("TD-SCDMA")
                            || subtypeName.equalsIgnoreCase("WCDMA")
                            || subtypeName.equalsIgnoreCase("CDMA2000")) {
                        return NetworkType.NETWORK_3G;
                    } else {
                        return NetworkType.NETWORK_UNKNOWN;
                    }
            }
        } else {
            return NetworkType.NETWORK_UNKNOWN;
        }
    }
    return NetworkType.NETWORK_NO;
}
获取 IP 地址
代码语言:javascript复制
/**
 * Return the ip address.
 * <p>Must hold {@code <uses-permission android:name="android.permission.INTERNET" />}</p>
 *
 * @param useIPv4 True to use ipv4, false otherwise.
 * @return the ip address
 */
@RequiresPermission(INTERNET)
public static String getIPAddress(final boolean useIPv4) {
    try {
        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        LinkedList<InetAddress> adds = new LinkedList<>();
        while (nis.hasMoreElements()) {
            NetworkInterface ni = nis.nextElement();
            // To prevent phone of xiaomi return "10.0.2.15"
            if (!ni.isUp() || ni.isLoopback()) continue;
            Enumeration<InetAddress> addresses = ni.getInetAddresses();
            while (addresses.hasMoreElements()) {
                adds.addFirst(addresses.nextElement());
            }
        }
        for (InetAddress add : adds) {
            if (!add.isLoopbackAddress()) {
                String hostAddress = add.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 "";
}
获取域名 IP 地址
代码语言:javascript复制
@RequiresPermission(INTERNET)
public static String getDomainAddress(final String domain) {
    InetAddress inetAddress;
    try {
        inetAddress = InetAddress.getByName(domain);
        return inetAddress.getHostAddress();
    } catch (UnknownHostException e) {
        e.printStackTrace();
        return "";
    }
}
根据 WiFi 获取网络 IP 地址
代码语言:javascript复制
@RequiresPermission(ACCESS_WIFI_STATE)
public static String getIpAddressByWifi() {
    @SuppressLint("WifiManagerLeak")
    WifiManager wm = (WifiManager) getApp().getSystemService(Context.WIFI_SERVICE);
    if (wm == null) return "";
    return Formatter.formatIpAddress(wm.getDhcpInfo().ipAddress);
}
网络状态改变监听器
代码语言:javascript复制
XNetwork.registerNetworkStatusChangedListener(new XNetwork.OnNetworkStatusChangedListener() {
         @Override
         public void onDisconnected() {
             
         }

         @Override
         public void onConnected(XNetwork.NetworkType networkType) {

         }
     });
wifi列表更新监听器
代码语言:javascript复制
XNetwork.addOnWifiChangedConsumer(new XApp.Consumer<WifiScanResults>() {
         @Override
         public void accept(WifiScanResults wifiScanResults) {
             
         }
     });
获取 WIFI 列表
代码语言:javascript复制
WifiScanResults wifiScanResults = XNetwork.getWifiScanResult();
List<ScanResult> scanResults = wifiScanResults.getFilterResults();

0 人点赞