Android获取当前网络状态和获取当前设备网络ip地址
16lz
2021-01-23
Android获取当前网络状态
/** * @Title: getNetWorkState * * @Description: 获取当前网络状态 * * @param context * @return int */public static int getNetWorkState(Context context) {final int network_none = -1;// 没有连接网络final int network_mobile = 0;// 移动网络final int network_wifi = 1;// 无线网络// 得到连接管理器对象ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_WIFI)) {return network_wifi;} else if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_MOBILE)) {return network_mobile;}} else {return network_none;}return network_none;}
Android获取当前设备网络ip地址
/** * @Title: getIpAddress * * @Description: 获取设备ip地址 * * @return String */public static String getIpAddress() {try {for (Enumeration enNetI = NetworkInterface.getNetworkInterfaces(); enNetI.hasMoreElements();) {NetworkInterface netI = enNetI.nextElement();for (Enumeration enumIpAddr = netI.getInetAddresses();enumIpAddr.hasMoreElements();) {InetAddress inetAddress = enumIpAddr.nextElement();if (inetAddress instanceof Inet4Address &&!inetAddress.isLoopbackAddress()) {return inetAddress.getHostAddress();}}}} catch (SocketException e) {e.printStackTrace();}return "";}